【发布时间】:2020-04-10 10:41:10
【问题描述】:
我有一个简单的绘图,我无法使用 scale_linetype_manual 根据绘图中的线型更改图例中的线型。
生成情节的代码是:
library(ggplot2)
x_1 <- rep(0:6, each = 2)
pdf_1 <- c(0,0.05,0.05,0.1,0.1,0.15,0.15,0.3,0.3,0.25,0.25,0.15,0.15,0)
x_2 <- rep(3:9, each = 2)
pdf_2 <- c(0,0.05,0.05,0.1,0.1,0.15,0.15,0.3,0.3,0.25,0.25,0.15,0.15,0)
data_1 <- data.frame(x_1, pdf_1,x_2,pdf_2)
ggplot()+
geom_line(data=data_1,aes(x=x_1, y=pdf_1, color="Forecaster_1"),linetype='solid',size=1)+
geom_line(data=data_1,aes(x=x_2, y=pdf_2, color="Forecaster_2"),linetype='dashed',size=1)+
labs(x = "x") +
labs(y = "PDF") +
scale_colour_manual(values = c('Forecaster_1' = 'cornflowerblue', 'Forecaster_2' = 'coral2')) +
scale_linetype_manual(values = c('Forecaster_1' = 'solid', 'Forecaster_2' = 'dashed'))
希望有人能帮我解决这个问题。
【问题讨论】:
-
您的代码不会为线型生成比例。因此
scale_linetype_manual无效。您需要先重塑数据。看看这篇文章的大致思路:Plotting two variables as lines using ggplot2 on the same graph(但不是哈德利的回答) -
这能回答你的问题吗? Add legend to ggplot2 line plot
-
@markus 我总是不愿意使用那个作为欺骗目标正是因为那个免责声明......也许有人可以让哈德利删除或更新他的答案
-
@markus 谢谢。有什么方法可以修复图例而不重塑和添加组变量?