我有一个 ggplot,其中包含由线连接的不同主题(x 轴)的两组点。为他们创造了一个传奇。然后我想为每个科目添加点的变换,例如算术平均值,并获得一个单独的图例来解释附加点(这些点不是用线连接的)。
有没有办法在 ggplot 中做到这一点?
library(tidyverse)
y1 <- c(10,20,25)
y2 <- c(20,40,30)
adf <- data.frame(x=c('a','b','c'),y1=y1,y2=y2)
ldf <- adf |> pivot_longer(cols=c(y1,y2), names_to='ymethod',values_to='yval')
p <- ggplot(data=ldf)+
geom_point(aes(x=x,y=yval, colour = ymethod)) +
geom_line(aes(x=x,y=yval, colour = ymethod,group=ymethod))
# want an separate legend for these (points not joined by lines)
# called 'Mean' showing a single black point
p <- p+geom_point(data=adf|>mutate(am=0.5*(y1+y2)),
aes(x=x,y=am))
# doesn't do what I want
#p <- p+geom_point(data=adf|>mutate(am=0.5*(y1+y2)),
# aes(x=x,y=am),col='black', show.legend = T)
# doesn't do what I want
#p <- p+geom_point(data=adf|>mutate(am=0.5*(y1+y2)),
# aes(x=x,y=am, col='black'), show.legend = T)
# doesn't do what I want
#p <- p+geom_point(data=adf|>mutate(am=0.5*(y1+y2)),
# aes(x=x,y=am, col='mean'), show.legend = T) +
# scale_color_manual(values=c('mean'='black'))
print(p)
ggplot(data=ldf)+
geom_point(aes(x=x,y=yval, colour = ymethod)) +
geom_line(aes(x=x,y=yval, colour = ymethod,group=ymethod)) +
geom_point(data=adf|>mutate(am=0.5*(y1+y2)),
aes(x=x,y=am, fill = "mean")) +
guides(fill=guide_legend(title=element_blank()))
创建于 2024-11-07,使用 reprex v2.0.2