繁体   English   中英

在ggplot中添加手动图例

[英]Adding manual legend in ggplot

我已经浏览了之前的类似问题,并且(我认为)已经完成了其中推荐的所有内容。 仍然没有得到我想要的输出。

我有一堆分布,我将它们显示在分面图中。 然后我通过它们画垂直线,代表不同的干预措施。

我正在尝试显示一个图例,其中包含分布的填充颜色以及这些额外线条的线条颜色。 据我所知,我做的一切都是正确的(在aes()设置颜色命令,使用scale_colour_manual()来定义图例等)。 我仍然只得到填充颜色的图例。

这是我的代码:

ggplot(modCosts, aes(x=cost)) + geom_density(aes(fill=group)) + theme_bw() +
  facet_wrap(~ country, scales="free") + scale_x_continuous(label = dollar) +
  scale_fill_brewer(palette = "RdGy", name = "Income group", labels = c("HIC" = "High income", "UMIC" = "Upper-middle income", "LIC" = "Low income")) + 
  labs(y = "Density", x = "Cost", title = "Medical costs of surgery\nActual vs. modeled") + 
  geom_vline(data = surgCosts, aes(xintercept = CS.tert.lo, color = "red4")) +
  geom_vline(data = surgCosts, aes(xintercept = CS.tert.hi, color = "red4")) + 
  geom_vline(data = surgCosts, aes(xintercept = CS.prim.lo, color = "red4"), lty = "dashed") + 
  geom_vline(data = surgCosts, aes(xintercept = CS.prim.hi, color = "red4"), lty = "dashed") + 
  geom_vline(data = surgCosts, aes(xintercept = Lap.tert.lo, color = "deepskyblue")) +
  geom_vline(data = surgCosts, aes(xintercept = Lap.tert.hi, color = "deepskyblue")) + 
  geom_vline(data = surgCosts, aes(xintercept = Lap.prim.lo, color = "deepskyblue"), lty = "dashed") + 
  geom_vline(data = surgCosts, aes(xintercept = Lap.prim.hi, color = "deepskyblue"), lty = "dashed") + 
  geom_vline(data = surgCosts, aes(xintercept = Fx.tert.lo, color = "yellowgreen")) + 
  geom_vline(data = surgCosts, aes(xintercept = Fx.tert.hi, color = "yellowgreen")) + 
  scale_color_manual(name = "Reported cost", values = c("red4" = "red4", "deepskyblue" = "deepskyblue", "yellowgreen" = "yellowgreen"),
                      labels = c("Int1", "Int2", "Int3")) +
  theme(axis.ticks = element_blank(), axis.text.y = element_blank(), legend.position = "right") 

这是我得到的输出: 在此处输入图片说明

任何帮助将不胜感激!

geom_vline(...) (以及_hline_abline )有一个show_guide=...参数,默认为FALSE 显然,大多数情况下,您不希望线条颜色显示在图例中。 这是一个例子。

df <- mtcars
library(ggplot2)
ggp <- ggplot(df, aes(x=wt, y=mpg, fill=factor(cyl))) +
  geom_point(shape=21, size=5)+
  geom_vline(data=data.frame(x=3),aes(xintercept=x, color="red"), show_guide=TRUE)+
  geom_vline(data=data.frame(x=4),aes(xintercept=x, color="green"), show_guide=TRUE)+
  geom_vline(data=data.frame(x=5),aes(xintercept=x, color="blue"), show_guide=TRUE)

ggp +scale_color_manual("Line.Color", values=c(red="red",green="green",blue="blue"),
                     labels=paste0("Int",1:3))

顺便说一句,如果您坚持使用颜色名称,则指定比例的更好方法是:

ggp +scale_color_identity("Line.Color", labels=paste0("Int",1:3), guide="legend")

产生上面相同的图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM