在ggplot中绘制图例

融合

我已经使用 ggplot2 生成了一个图,但是我在创建自定义图例时遇到了困难。我的情节是这样的:在此处输入图片说明

黑色部分是ggplot创建的,红色部分是我需要添加的部分。点旁边的矩形实际上是一个标签,但我需要标签轮廓(一个矩形)作为图例的一部分. 我已经提到了相关的问题,但到目前为止我还没有看到类似的问题,因为我认为这个问题在图例中更像是“绘图”而不是“映射”。

有人可以帮我吗?由于我有很多图,我更愿意用 R 解决这个问题,而不是用图像编辑器手动编辑图。谢谢!

编辑:根据要求,一个可重复的样本。抱歉没有提前添加!

library(ggrepel)
dput(df)
structure(list(ID = 1L, Date = structure(16259, class = "Date"), 
    Primary = 0.009, Secondary = structure(1L, .Label = "Label ABC", class = "factor")), row.names = c(NA, 
-1L), class = "data.frame", .Names = c("ID", "Date", "Primary", 
"Secondary"))

ggplot(df, aes(Date, Primary)) + geom_point(aes(shape=ifelse(Primary>0, "Detected", "Not Detected"))) + geom_label_repel(aes(label=Secondary)) + scale_shape_manual(values=c("Not Detected"=1,"Detected"=19),name="Primary") + theme_bw()
dmi3kno

您的数据:

df <- data.frame(stringsAsFactors=FALSE,
           ID = c(1L, 2L),
           Date = c("2014-07-08", "2017-03-12"),
           Primary = c(0.009, -0.05),
           Secondary = c("Label ABC", "Label BCD")
)

这是本机ggplot解决方案。基本上每个点后面都有一个隐藏的矩形,它是图例中显示的矩形。您需要将它放在不同的 aestetic 上,例如color,而点由 区分shape,以便它不会与点合并为一个图例项。

library(ggrepel)


df %>% 
  mutate(isDetected=ifelse(Primary>0, "Detected", "Not Detected")) %>% 
  ggplot(aes(Date, Primary)) + 
    geom_rect(aes(xmin=Date, xmax=Date, ymin=Primary, ymax=Primary, color=isDetected), 
              fill="white")+
    geom_point(aes(shape=isDetected), size=3) + 
    geom_label_repel(aes(label=Secondary, color=isDetected), show.legend = FALSE) + 
    scale_shape_manual(values=c("Not Detected"=1,"Detected"=19))+
    labs(shape="Primary",
        color="Secondary")+
    theme_bw()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章