我正在与趋势线线图ggplot2有geom_line,geom_point和geom_smooth。我的代码与此类似。
year <- as.character(2011:2020)
x <- c(12, 13, 12.5, 14, 15, 17, 16, 18, 18, 19)
y <- c(25, 28, 30, 27, 30, 31, 30, 31, 33, 33)
dat <- data.frame(year, x, y) %>%
pivot_longer(cols = c(x,y), names_to = "item", values_to = "price")
ggplot(dat, aes(x=year, y=price, group=item, col=item))+
geom_line()+
geom_point(aes(shape=item))+
geom_smooth(method = "loess", se = FALSE, size=0.8, linetype="dotdash")+
labs(x = "Year",
y = "Price")
Run Code Online (Sandbox Code Playgroud)
我想geom_smooth在图例中单独包含趋势线,以便图例中有四个项目 - x、y、x 的趋势线和 y 的趋势线。我应该如何进行?
这是获取geom_smooth.
首先,您需要添加linetype作为 ofaes的参数geom_smooth。然后,您可以通过使用自定义它scale_linetype_manual来获得两个标签x,并y与不同的名称,以便从分离item的传说。
使用guides,您可以修改此图例并添加与用于geom_point和 的颜色模式相同的颜色模式geom_line:
ggplot(dat, aes(x=year, y=price, group = item, color = item))+
geom_line()+
geom_point(aes(shape= item))+
geom_smooth(aes(linetype = item), method = "loess", se = FALSE, size=0.8)+
labs(x = "Year",
y = "Price")+
scale_linetype_manual(values = c("dotdash","dotdash"), name = "trendline", labels = c("x", "y"))+
guides(linetype = guide_legend(override.aes = list(linetype = c("dotdash", "dotdash"),color = scales::hue_pal()(2))))
Run Code Online (Sandbox Code Playgroud)
它看起来像你想要的吗?
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |