保留x标签的ggplot2中时间序列的重叠

时间:2012-01-17 14:46:18

标签: r ggplot2

如何与ggplot2重叠两个时间序列并保留两个X标签(一个是1970,另一个是1980)?

这是我的数据集和我用来绘制每个图形的代码的概述。

> dataset1.data
      Date Obs
1 1/1/1970 2.0
2 1/2/1970 1.0
3 1/3/1970 0.0
4 1/4/1970 0.0
5 1/5/1970 0.5
6 1/6/1970 5.1
7 1/7/1970 0.0
8 1/8/1970 0.0

> dataset2.data
      Date Obs
1 1/1/1980 3.0
2 1/2/1980 0.5
3 1/3/1980 0.5
4 1/4/1980 5.0
5 1/5/1980 0.4
6 1/6/1980 6.2
7 1/7/1980 9.0
8 1/8/1980 1.3

qplot(main="Observations 1")+xlab("Date")+ylab("Obs")+
geom_point(data = dataset1.data,aes(Date, Obs, colour="blue"),alpha = 0.7,na.rm = TRUE)+
scale_colour_identity("Legend", breaks=c("blue"), labels="1970")

qplot(main="Observations 2")+xlab("Date")+ylab("Obs")+
geom_point(data = dataset2.data,aes(Date, Obs, colour="red"),alpha = 0.7,na.rm = TRUE)+
scale_colour_identity("Legend", breaks=c("red"), labels="1980")

1 个答案:

答案 0 :(得分:2)

我会将它们放在一个数据集中,然后使用新的Year变量进行颜色审美:

dataset1.data = read.table('dataset1.txt')
dataset2.data = read.table('dataset2.txt')

dataset1.data$Date = as.Date(dataset1.data$Date, format='%m/%d/%Y')
dataset2.data$Date = as.Date(dataset2.data$Date, format='%m/%d/%Y')

data = rbind(dataset1.data, dataset2.data)
data = transform(data, MonthDay=gsub('(.+)-(.+-.+)', '\\2', data$Date), Year=gsub('(.+)-(.+-.+)', '\\1', data$Date))

qplot(main="Observations 1")+xlab("Date")+ylab("Obs")+geom_point(data = data,aes(MonthDay, Obs, colour=Year),alpha = 0.7,na.rm = TRUE)

enter image description here

也可以通过编辑网格对象来实现。例如,请参阅:https://github.com/hadley/ggplot2/wiki/Editing-raw-grid-objects-from-a-ggplot