我有一个情节,我想通过灰线将点连接在一起。我想知道有没有办法在点周围添加边框,以便线接触到它们的边界,或者甚至不接触点,而不是直接进入点的中心。我正在使用 ggplot。
我已经为任何想要使用它的人提供了一些示例数据。
df <- data.frame(Name = c("a","b","c","d","e","f"),
Category = c("x","y","x","y","x","y"),
N = c(500,540,470,500,480,520))
我还包括了我的 ggplot 代码,用于制作上面的图
df %>%
arrange(N) %>%
mutate(Name = factor(Name, levels = unique(Name))) %>%
ggplot(aes(Name, N)) +
geom_point(aes(color = Category)) +
geom_point(shape = 1,size = 2,colour = "black") +
scale_colour_manual(values = c("green","cyan")) +
geom_line(aes(group = Name), colour = "grey", alpha = 1) +
theme(
axis.title.x = element_blank(),
axis.ticks = element_blank(),
axis.title.y = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_blank(),
panel.background = element_rect(fill = "white"),
legend.position = "none")
编辑:
如下所示,在将线切换到点之前的注释中,会产生以下结果:
I don't think your plot is reproducible with unique letters for Name
. To fit a vertical line, Name
requires unique 'pairs' of letters. In your call to ggplot()
, Name
is mapped onto the x-axis and also passed to the group aesthetic, which produces a line between two points at the same x-value. For example, your data frame should look something like the following:
Name Category N
1 A x 500
2 A y 540
3 B x 470
4 B y 500
5 C x 480
6 C y 520
Note, each group consists of two observations, which should only vary along the vertical dimension.
I imagine your data frame was corrected to account for this, but it isn't clear from the code you supplied. It appears @erocoar already addressed your principal concern in the comments. It is a simple matter of precedence with respect to the geom_
layers.
我使用新的数据框重现了您的情节。请记住,对于这项工作,我们必须对每组进行多次观察。
library(dplyr)
library(ggplot2)
df <- data.frame(
Name = rep(c("A", "B", "C"), each = 2), # unique pairs (two observations per group)
Category = c("x", "y", "x", "y", "x", "y"),
N = c(500, 540, 470, 500, 480, 520)
)
df %>%
arrange(N) %>%
mutate(Name = factor(Name, levels = unique(Name))) %>%
ggplot(aes(x = Name, y = N)) +
geom_line(aes(group = Name), colour = "grey", alpha = 1) + # feeding Name to the group aesthetic
geom_point(aes(color = Category)) +
geom_point(shape = 1,size = 2,colour = "black") +
scale_colour_manual(values = c("green", "cyan")) +
theme(
axis.title.x = element_blank(),
axis.ticks = element_blank(),
axis.title.y = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major.x = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_blank(),
panel.background = element_rect(fill = "white"),
legend.position = "none")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句