在ggplot中绘制来自同一数据帧的多个变量 [英] Plotting multiple variables from same data frame in ggplot
问题描述
我有一个可以这样定义的数据集:
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的新手,并且不需要做这之前。试图在StackOverflow上模拟类似问题的答案会产生错误。
例如...
library(ggplot2)
ggplot(df,aes(x = Week,y = value,color = variable))+
geom_line()
...在
I have a data set which could be defined thus:
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)
I want to plot all three of the y's over time on the same ggplot (with manual colors and linetype for each one), but I'm new to ggplot and have not had to do this before. Trying to emulate answers to similar questions on StackOverflow is delivering errors.
For instance...
library(ggplot2)
ggplot(df, aes(x = Week, y = value, colour = variable)) +
geom_line()
...as in this question gives the error Error in eval(expr, envir, enclos) : object 'value' not found
.
But trying as in the answer to 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"))
...gives three instances of the error geom_path: Each group consists of only one observation. Do you need to adjust the group
aesthetic?
. Can I get some assistance, please?
Actually this is what you really want I think:
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"))
Note that leaving the group=variable
out will cause the following dreaded message:
geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
yielding:
这篇关于在ggplot中绘制来自同一数据帧的多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!