r - 如何在ggplot2中为hline添加图例

标签 r ggplot2

我的数据是这样的:

month=c("Jan","Feb","Mar","Apr","May","Jun")
rate=c(70,80,90,85,88,76) 
dd=data.frame(month,rate)
dd$type="Rate"
dd$month=factor(dd$month)

我试着像这样创建情节:

ggplot(dd,aes(x=month,y=rate,color=type)) + 
  geom_point(aes(x=month,y=rate, group=1), size=2) +
  geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = rate, group=1), size=1) + 
  geom_hline(aes(yintercept=85), linetype='dashed',colour="#F8766D", show.legend=T) +
  labs(y="", x="") + 
  scale_colour_manual(values = c("#00BFC4")) +
  scale_fill_discrete(limits = c("Target")) +
  theme(legend.position="bottom") +
  theme(legend.title = element_blank()) 

enter image description here

如您所见,Rate 和 Target 的图例重叠在一起(绿线中有红色虚线),我想知道如何以正确的方式为 Target 和 Rate 创建图例。谢谢!

最佳答案

实现您想要的结果的一个选择是根据美学进行映射并使用 scale_xxx_manual 而不是通过参数设置颜色、线型...:

month=c("Jan","Feb","Mar","Apr","May","Jun")
rate=c(70,80,90,85,88,76) 
dd=data.frame(month,rate)
dd$type="Rate"
dd$month=factor(dd$month)

library(ggplot2)

ggplot(dd,aes(x=month,y=rate, color="Rate", linetype = "Rate")) + 
  geom_point(aes(x=month,y=rate, shape = "Rate"), size=2) +
  geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = rate, group=1, size = "Rate")) + 
  geom_hline(aes(yintercept=85, color = "Target", linetype = "Target", size = "Target")) +
  labs(y = NULL, x= NULL, color = NULL, linetype = NULL, shape = NULL, size = NULL) + 
  scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D")) +
  scale_linetype_manual(values = c(Rate = "solid", Target = "dashed")) +
  scale_shape_manual(values = c(Rate = 16, Target = NA)) +
  scale_size_manual(values = c(Rate = 1, Target = .5)) +
  theme(legend.position="bottom")

关于r - 如何在ggplot2中为hline添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68468334/

相关文章:

r - 如何在geom_segment中获取T型箭头?

r - 编写自定义 R 函数以在 dbplyr SQL 中使用

r - x 轴上以可变条形宽度作为日期范围的条形图

r - 在ggplot中的连续轴上格式化数字

r - 创建半 donut 或议会席位图表

r - ggplot2 关于我无法使用 `na.rm=T` 禁用的缺失的警告

r - 如何修复 rep(1,N) : invalid 'times' argument when using glmnet 中的错误

r - 如何将 for 循环与特殊 seq 一起使用

r - 可以使用 ggimage 包中的 geom_image() 来保留图像纵横比吗?

r - 控制ggplot2图例位置而不改变轴的比例