我在合并图例时遇到问题,当前结果已分别指定线型、大小、形状和颜色。
\n我的数据如下所示:
\nlibrary(ggplot2)\nlibrary(dplyr)\nlibrary(reshape2)\nlibrary(patchwork)\nlibrary(hrbrthemes)\n\nrate="rate"\nJul="0.5\xe2\x80\xb0"\nAug="0.6\xe2\x80\xb0"\nSep="0.7\xe2\x80\xb0"\n\ndf <- data.frame(rate,Jul,Aug,Sep)\ndf\nd=melt(df,measure.vars = names(df)[2:4])\nd\nd$month=as.factor(d$variable)\nd$percent=as.numeric(gsub("\xe2\x80\xb0","",d$value))\n我使用 ggplot2 绘制数据:
\nggplot(d,aes(x=month,y=percent)) + \n  geom_point(aes(x=month,y=percent,color="Rate",shape="Rate"), size=2) +\n  geom_text(aes(label = paste(format(percent, digits = 4, format = "f"), "\xe2\x80\xb0")), \n            color="black",vjust = -0.5, size = 3.5) +\n  geom_line(aes(x = month, y = percent, group=1, color="Rate",linetype = "Rate",size="Rate")) + \n  geom_hline(aes(yintercept=1,color="Target",linetype="Target",size="Target"))+\n  scale_y_continuous(breaks = seq(0,1.1,0.2), \n                     labels = paste0(seq(0,1.1,0.2)," \xe2\x80\xb0")) +\n  expand_limits(y = c(0, 1.1)) +\n  labs(y="", x="") + \n  theme(plot.title = element_text(hjust = 0.5)) + \n  scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D")) +\n  scale_linetype_manual(values = c(Rate = "solid", Target = "dashed")) +\n  scale_shape_manual(values = c(Rate = 16, Target = NA)) +\n  scale_size_manual(values = c(Rate = 1, Target = .7)) +\n  theme(legend.key=element_blank(),legend.position="bottom") \nlegend的结果看起来很乱:
\n\n我希望图例如下所示:
\n\n那么如何修改代码来合并图例呢?
\n非常感谢!
\n如果我们给图例赋予相同的名称,ggplot 将尝试合并它们:
...
scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D"), name = "Legend") +
  scale_linetype_manual(values = c(Rate = "solid", Target = "dashed"), name = "Legend") +
  scale_shape_manual(values = c(Rate = 16, Target = NA), name = "Legend") +
  scale_size_manual(values = c(Rate = 1, Target = .7), name = "Legend") +
  theme(legend.key=element_blank(),legend.position="bottom")