使用 ggplot() 在同一图上绘制多个时间序列 [英] Plotting multiple time series on the same plot using ggplot()

查看:49
本文介绍了使用 ggplot() 在同一图上绘制多个时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 R 相当陌生,正在尝试使用 ggplot2 同时绘制两条时间序列线(当然,使用不同的颜色).

I am fairly new to R and am attempting to plot two time series lines simultaneously (using different colors, of course) making use of ggplot2.

我有 2 个数据框.第一个有X 的百分比变化"和日期"列.第二个也有Y 的百分比变化"和日期"列,即两者都有一个具有相同值的日期"列,而百分比变化"列具有不同的值.

I have 2 data frames. the first one has 'Percent change for X' and 'Date' columns. The second one has 'Percent change for Y' and 'Date' columns as well, i.e., both have a 'Date' column with the same values whereas the 'Percent Change' columns have different values.

我想在单个图上使用 ggplot2 绘制相对于日期"(两者通用)的百分比变化"列.

I would like to plot the 'Percent Change' columns against 'Date' (common to both) using ggplot2 on a single plot.

我在网上找到的示例使用具有不同变量的相同数据框来实现这一点,但我无法找到任何使用 2 个数据框来绘制绘图的示例.我不想将两个数据框绑定在一起,我想让它们分开.这是我正在使用的代码:

The examples that I found online made use of the same data frame with different variables to achieve this, I have not been able to find anything that makes use of 2 data frames to get to the plot. I do not want to bind the two data frames together, I want to keep them separate. Here is the code that I am using:

ggplot(jobsAFAM, aes(x=jobsAFAM$data_date, y=jobsAFAM$Percent.Change)) + geom_line() +
  xlab("") + ylab("")

但是这段代码只产生一行,我想在它上面添加另一行.任何帮助将非常感激.TIA.

But this code produces only one line and I would like to add another line on top of it. Any help would be much appreciated. TIA.

推荐答案

ggplot 允许你有多个层,这就是你应该在这里利用的.

ggplot allows you to have multiple layers, and that is what you should take advantage of here.

在下面创建的图中,您可以看到有两个 geom_line 语句命中您的每个数据集并将它们一起绘制在一个图中.如果您希望添加任何其他数据集、绘图甚至图表的特征(例如轴标签),您可以扩展该逻辑.

In the plot created below, you can see that there are two geom_line statements hitting each of your datasets and plotting them together on one plot. You can extend that logic if you wish to add any other dataset, plot, or even features of the chart such as the axis labels.

library(ggplot2)

jobsAFAM1 <- data.frame(
  data_date = runif(5,1,100),
  Percent.Change = runif(5,1,100)
)

jobsAFAM2 <- data.frame(
  data_date = runif(5,1,100),
  Percent.Change = runif(5,1,100)
)

ggplot() + 
  geom_line(data = jobsAFAM1, aes(x = data_date, y = Percent.Change), color = "red") +
  geom_line(data = jobsAFAM2, aes(x = data_date, y = Percent.Change), color = "blue") +
  xlab('data_date') +
  ylab('percent.change')

这篇关于使用 ggplot() 在同一图上绘制多个时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆