我有一个可以这样定义的数据集:
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)
Run Code Online (Sandbox Code Playgroud)
我想在同一个 ggplot 上绘制所有三个 y 随着时间的推移(每个都有手动颜色和线型),但我是 ggplot 新手,以前不需要这样做。尝试模拟 StackOverflow 上类似问题的答案会导致错误。
例如...
library(ggplot2)
ggplot(df, aes(x = Week, y = value, colour = variable)) +
geom_line()
Run Code Online (Sandbox Code Playgroud)
...正如在这个问题中给出的错误Error in eval(expr, envir, enclos) : object 'value' not found。
但尝试回答这个问题......
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"))
Run Code Online (Sandbox Code Playgroud)
...给出了三个错误实例geom_path: Each group consists of only one observation. Do you need to adjust the group
aesthetic?。我可以得到一些帮助吗?
事实上,我认为这才是你真正想要的:
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"))
Run Code Online (Sandbox Code Playgroud)
请注意,忽略该group=variable选项将导致出现以下可怕的消息:
Run Code Online (Sandbox Code Playgroud)geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
产量:
| 归档时间: |
|
| 查看次数: |
28107 次 |
| 最近记录: |