gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:37:59 29 4
gpt4 key购买 nike

我的数据是这样的:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com