在图例中添加线型虚线和颜色 [英] Getting linetype dashed and color in the legend

查看:21
本文介绍了在图例中添加线型虚线和颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试着把Legent放在我的图画上。 我正在构造,以使线型反映在传奇中。 我有这个代码:

legend_1 <- "a"
legend_2 <- "b"
colours <- t(c('green', 'red'))
colnames(colours) <-c(legend_1, legend_2)

df <- data.frame(a=1:3,b=c(5,6,-1),c=c(3,5,4))
ggplot(df, aes(x=a)) + #byg plot
  geom_line(aes(y=b, color = legend_1), size=1) + #tilføj linje
  geom_line(aes(y=c, color = legend_2), size=1,linetype="dashed")+  #tilføj ny linje

theme_gray() + #tilføj tema
  labs(title = "title", y = 'ppm', x= 'Tid (s)', color = '') + #tilføj titel og akselabels
  theme(plot.title = element_text(hjust = 0.5)) + #centrerer titel
  scale_color_manual(values = colours)

我能做些什么?

推荐答案

基本上与添加颜色图例相同。在linetype上映射,而不是将其设置为仅一行的参数。通过scale_linetype_manual添加您想要的线型,确保两个图例使用相同的标题(我只需通过NULLinsidelabs删除标题):

library(ggplot2)

legend_1 <- "a"
legend_2 <- "b"
colours <- t(c('green', 'red'))
colnames(colours) <-c(legend_1, legend_2)

lty <- c(a = "solid", b = "dashed")

df <- data.frame(a=1:3,b=c(5,6,-1),c=c(3,5,4))
ggplot(df, aes(x=a)) + #byg plot
  geom_line(aes(y=b, color = legend_1, linetype = legend_1), size=1) + #tilføj linje
  geom_line(aes(y=c, color = legend_2, linetype = legend_2), size=1)+  #tilføj ny linje
  theme_gray() + #tilføj tema
  labs(title = "title", y = 'ppm', x= 'Tid (s)', color = NULL, linetype = NULL) + #tilføj titel og akselabels
  theme(plot.title = element_text(hjust = 0.5)) + #centrerer titel
  scale_color_manual(values = colours) +
  scale_linetype_manual(values = lty)

这篇关于在图例中添加线型虚线和颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆