ggplot 和 R:随时间变化的两个变量
我想知道如何制作,以便在以下示例数据集中将 x 和 y 绘制在水平轴中框架的每个元素的垂直轴上。我如何使用 ggplot2 做到这一点?
x, y = 变量,frame = YYYYMM
示例数据:
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")
我已经能够将一个绘制在一条线上,但似乎它没有将我的框架识别为分类的(并非如此,我也不知道如何更改它)至此)。
p <- ggplot(df, aes(x=frame, y=x))
p + geom_line()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要融化您的数据:
这就是对您的数据框的作用:
You need to melt your data:
This is what that does to your data frame:
这是一个相当晚的答案,但如果您希望您的框架变量解释日期(一年中的月份),那么请将其转换为日期。
然后,您可以使用
scale_x_date
和scales
包来格式化 x 轴This is a rather late answer, but if you want your
frame
variable intepreted date (month of the year), then convert it to a date.You can then use
scale_x_date
and thescales
package to format the x-axis