gpt4 book ai didi

r - 如何获取 geom_segment 显示图例

转载 作者:行者123 更新时间:2023-12-02 01:38:00 27 4
gpt4 key购买 nike

下面的图有 2 个部分。

如何为线段添加图例?

理想情况下,最终结果有 2 个图例:

  1. 其中一个是当前的“点图例”
  2. 另一个图例是一个带有红色虚线标记为“段图例”的单个图例

这是代码

set.seed(11)
x = rnorm(100)

y = rnorm(100)

dat = data.frame(x = x, y = y)

ggplot(dat,aes(x=x,y=y)) + geom_point(aes(color="blue") ) +
geom_segment(aes(x = -2, xend = 2, y = 0, yend = 2), color="red", linetype="dashed", size=1.2) +
geom_segment(aes(x = -1, xend = 1, y = -2, yend = -1), color="red", linetype="dashed", size=1.2) +
scale_color_manual(name = "",values = c("blue"),labels="point legend")

enter image description here

最佳答案

#Generate data
x = rnorm(100)
y = rnorm(100)
dat = data.frame(x = x, y = y)

#Create new variable with same value as desired legend label
dat$cat<-rep('segment legend', 100)
colnames(dat)<-c("x","y","segment legend") #change column name to legend label

#Plot
ggplot(dat,aes(x=x,y=y)) + geom_point(aes(color="blue") ) +
geom_segment(aes(x = -2, xend = 2, y = 0, yend = 2, linetype=`segment legend`),
color="red", size=1.2) + #move linetype= to inside aesthetics
geom_segment(aes(x = -1, xend = 1, y = -2, yend = -1, linetype=`segment legend`),
color="red", size=1.2) + #move linetype= to inside aesthetics
scale_color_manual(name = "",values = c("blue"),labels="point legend")+
scale_linetype_manual("segment legend",values=c("segment legend"=2))+
theme(legend.title=element_blank())

enter image description here

关于r - 如何获取 geom_segment 显示图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39552125/

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