在每个面板中添加不同的geom_segment

4

我有以下代码,它可以正常工作。问题是,我想添加"k"并绘制类似于"z"的直线,但"k"是一个不同数字的向量。 "k"中的每个元素都应绘制为创建的三个面之一上的一条线。如果k是一个单值,我只需重复geom_segment()命令,并使用不同的y限制即可。有没有简单的方法来做到这一点?最终输出应该看起来像附件,假设我可以画一条直线。

x <- iris[-1:-3]
bw <- 1
nbin <- 100
y <- head(iris, 50)[2]
z <- 1
k <- c(2, 3, 4)
    
ggplot(x, aes(x = Petal.Width)) +
  geom_density(aes(y = bw *..count.., fill = Species), size = 1, alpha = 0.4) + 
  geom_segment(aes(x = 5, y = 250, xend = z, yend = 250, color = "red")) +
  facet_wrap(~Species)+
  scale_x_continuous(labels = scales::math_format(10^.x), limits = c(0, 5), expand = c(0,0)) + 
  scale_y_continuous(expand = c(0,0), limits = c(0, NA)) +
  annotation_logticks(sides = "b", short=unit(-1,"mm"), mid=unit(-2,"mm"), long=unit(-3,"mm")) +
  coord_cartesian(clip='off') + theme(panel.background = element_blank(), 
                                      panel.border = element_rect(colour = "black", fill=NA)) 

enter image description here


可能是这样,但只要该行存在,它的位置并不重要。我可以在geom_segment中调整y值。 - user13589693
2个回答

2
你可以尝试这个。假设你的图形保存为p1。
k_data = data.frame(k, Species = levels(x$Species))
p1 + geom_segment(data = k_data, aes(x =5, y = 200, xend = k, yend = 200), 
                  color = "blue", inherit.aes = F)  

enter image description here

这句话的意思是:创建一个包含k和Species两列的数据框,并且在使用geom图层时,设置inherit.aes = F来仅使用该数据。

我也尝试过不加 inherit.aes = F,但输出结果仍然相同。你认为这样做有必要吗? - user13589693
你说得对。在这种情况下没问题。如果辅助数据中有进一步的列,例如具有相同名称,则您的图例甚至绘图可能会被破坏。 - Roman

0
在这个解决方案中,k 的值通过管道的方式成为了正在绘制的数据集的一部分。它是数据集的临时修改,因为它既没有被重新分配给它本身,也没有被分配给任何其他数据集。
library(ggplot2)
library(dplyr)

x <- iris[-1:-3]
str(x)
bw <- 1
nbin <- 100
y <- head(iris, 50)[2]
z <- 1
k <- c(2, 3, 4)

x %>%
  mutate(k = rep(k, each = 50)) %>%
  ggplot(aes(x = Petal.Width)) +
  geom_density(aes(y = bw *..count.., fill = Species), size = 1, alpha = 0.4) + 
  geom_segment(aes(x = 5, y = 250, xend = z, yend = 250), color = "red") +
  geom_segment(aes(x = 5, y = 200, xend = k, yend = 200), color = "blue") +
  facet_wrap(~Species)+
  scale_x_continuous(labels = scales::math_format(10^.x), limits = c(0, 5), expand = c(0,0)) + 
  scale_y_continuous(expand = c(0,0), limits = c(0, NA)) +
  annotation_logticks(sides = "b", short=unit(-1,"mm"), mid=unit(-2,"mm"), long=unit(-3,"mm")) +
  coord_cartesian(clip='off') + 
  theme(panel.background = element_blank(), 
        panel.border = element_rect(colour = "black", fill=NA)) 

enter image description here


我选择了Roman的答案,只是因为在我的实际数据集中,数据集的大小可能会因物种而异,所以在mutate中添加“each = 50”不会起作用,需要进行一些调整。 - user13589693
@user13589693 你说得对,Roman的答案更好。 - Rui Barradas
1
我不确定哪种更好,这取决于数据。您可以使用 mutate(k = rep(k, each = n()/nlevels(Species))) 来泛化该函数。 - Roman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接