ggplot和R:随着时间的推移两个变量 [英] ggplot and R: Two variables over time
本文介绍了ggplot和R:随着时间的推移两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何使x和y在下面的示例数据集中绘制在横轴上的每个帧的每个元素的纵轴上。
$ b $ x $,$ =变量,frame = YYYYMM
示例数据:如何使用ggplot2执行此操作?
df < - 结构(列表(x = c(0.000892333625290767,0.0161153931761482,
0.0188150880795816,0.0268699106638318,0.018657330651898, 0.0101065034206662,
0.00154410447630379),y = c(1.35172948829027,0.59654026447333,
0.685835030118683,0.741545898152761,1.09653338596292,0.1119448208345102,
0.104092642854814),frame = c(200912,201001,201002,201003,
201004,201005,201006)),.Names = c(x,y,frame),row.names = c(1,
2,3, 4,5,6,7),class =data.frame)
我已经能够将其中一个绘制成一行,但它似乎并没有将我的框架识别为分类的(并非如此,也不知道如何将其更改为这样)。
p < - ggplot(df,aes(x = frame,y = x))
p + geom_line )
解决方案
您需要融化数据:
library(reshape2)
dfm = melt(df,id.vars ='frame')
ggplot(dfm ,aes(x = frame,y = value,color = variable))+ geom_line()
是什么对你的数据框:
> dfm
框架变量值
1 200912 x 0.0008923336
2 201001 x 0.0161153932
3 201002 x 0.0188150881
4 201003 x 0.0268699107
5 201004 x 0.0186573307
6 201005 x 0.0101065034
7 201006 x 0.0015441045
8 200912 y 1.3517294883
9 201001 y 0.5965402645
10 201002 y 0.6858350301
11 201003 y 0.7415458982
12 201004 y 1.0965333860
13 201005 y 0.1194482083
14 201006 y 0.1040926429
I'd like to know how to make it so that x and y, in the following example data set are plotted on the vertical axis for each element of frame in the horizontal axis. How do I do this with ggplot2?
x, y = variables, frame = YYYYMM
Example Data:
df <- structure(list(x = c(0.000892333625290767, 0.0161153931761482,
0.0188150880795816, 0.0268699106638318, 0.018657330651898, 0.0101065034206662,
0.00154410447630379), y = c(1.35172948829027, 0.59654026447333,
0.685835030118683, 0.741545898152761, 1.09653338596292, 0.119448208345102,
0.104092642854814), frame = c(200912, 201001, 201002, 201003,
201004, 201005, 201006)), .Names = c("x", "y", "frame"), row.names = c("1",
"2", "3", "4", "5", "6", "7"), class = "data.frame")
I've been able to get one plotted in a line, but it seems that it's not recognizing my frame as categorical (not that it is, nor do I know how to change it to such).
p <- ggplot(df, aes(x=frame, y=x))
p + geom_line()
解决方案
You need to melt your data:
library(reshape2)
dfm = melt(df, id.vars='frame')
ggplot(dfm, aes(x=frame, y=value, colour=variable)) + geom_line()
This is what that does to your data frame:
> dfm
frame variable value
1 200912 x 0.0008923336
2 201001 x 0.0161153932
3 201002 x 0.0188150881
4 201003 x 0.0268699107
5 201004 x 0.0186573307
6 201005 x 0.0101065034
7 201006 x 0.0015441045
8 200912 y 1.3517294883
9 201001 y 0.5965402645
10 201002 y 0.6858350301
11 201003 y 0.7415458982
12 201004 y 1.0965333860
13 201005 y 0.1194482083
14 201006 y 0.1040926429
这篇关于ggplot和R:随着时间的推移两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文