我有一个可以定义的数据集:
Week <- c("2015_52", "2016_01", "2016_02", "2016_03", "2016_04")
y1 <- runif(5, 0, 1)
y2 <- runif(5, 0, 1)
y3 <- runif(5, 0, 1)
df <- data.frame(Week, y1, y2, y3)
我想在同一个ggplot上绘制所有三个y(在每个ggplot上都有手动颜色和线型),但我是ggplot的新手并且之前没有这样做过。试图在StackOverflow上模拟类似问题的答案会导致错误。
例如......
library(ggplot2)
ggplot(df, aes(x = Week, y = value, colour = variable)) +
geom_line()
...与this question中一样,错误为Error in eval(expr, envir, enclos) : object 'value' not found
。
但尝试回答this question ......
ggplot() +
geom_line(data = df,
aes(x = Week, y = y1,
color = "black", linetype = "solid")) +
geom_line(data = df,
aes(x = Week, y = y2,
color = "red", linetype = "solid")) +
geom_line(data = df,
aes(x = Week, y = y3,
color = "orange", linetype = "dashed"))
...给出错误geom_path: Each group consists of only one observation. Do you need to adjust the group
aesthetic?
的三个实例。我可以得到一些帮助吗?
答案 0 :(得分:4)
实际上这是你真正想要的:
library(ggplot2)
library(reshape2)
set.seed(123)
Week <- c("2015_52", "2016_01", "2016_02", "2016_03", "2016_04")
y1 <- runif(5, 0, 1)
y2 <- runif(5, 0, 1)
y3 <- runif(5, 0, 1)
df <- data.frame(Week, y1, y2, y3)
mdf <- melt(df,id.vars="Week")
ggplot(mdf, aes( x=Week, y=value, colour=variable, group=variable )) +
geom_line() +
scale_color_manual(values=c("y1"="black","y2"="red","y3"="orange")) +
scale_linetype_manual(values=c("y1"="solid","y2"="solid","y3"="dashed"))
请注意,将group=variable
退出将导致以下可怕消息:
geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
得到以下特性: