在多个ggplots之间设置常用的年份颜色?

时间:2015-03-11 07:05:08

标签: r ggplot2 data-visualization

我有一个清理过的数据集(DropBox:[[[删除 - 如果你需要工作实例的更新副本评论]]] 2001年和2014年之间的支出。我有三个图 - 一个箱图和两个分散 - 我grid.arrange进入一个列进行比较。出于这个原因,我希望这些年份从上到下排列,并且每年在图表之间只有一种颜色 - 再次进行比较。

到目前为止,这是我的产品(一切都在为此而努力,只是不确定如何对齐映射)

require(ggplot2)
require(gridExtra)
require(ggthemes)
require(lubridate)

options(scipen=999)

date <- exp.s$Date
amount <- exp.s$Amount
N <- exp.s$total
xy <- data.frame(date, amount, N)

#boxplot, color by year of payment
b1<-ggplot(xy, aes(x = as.factor(year(date)), amount)) + 
 geom_boxplot(aes(fill = as.factor(exp.s$start_year))) +
 scale_color_gdocs() + 
 theme_gdocs()

#jitter plot, color by year of payment
b2<-ggplot(xy, aes(x = as.factor(year(date)), amount))  + 
 geom_jitter(alpha=I(.8), aes(color=as.factor(year(date)), size = exp.s$tot)) + 
 scale_color_gdocs() + theme_gdocs()

#jitter, color by contract start year
b3<-ggplot(xy, aes(x = as.factor(year(date)), amount))  + 
 geom_jitter(alpha=I(.9), aes(color=as.factor(exp.s$start_year), size = exp.s$tot)) + 
 scale_color_gdocs() + theme_gdocs()


grid.arrange(b1, b2, b3, ncol=1)

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试以下:

require(ggplot2)
require(gridExtra)
require(ggthemes)
require(lubridate)

options(scipen=999)

#read data
exp.s <- read.csv("2001_2014_Expenditures_Cleaned_Hashed.csv")

#make same levels for 2 variables 
mylevels <- as.character(sort(unique(c(year(exp.s$Date),exp.s$start_year))))

#data prep
xy <- data.frame(
  mydate = exp.s$Date,
  mydateYYYY = factor(year(exp.s$Date),levels = mylevels),
  start_year = factor(exp.s$start_year,levels = mylevels),
  amount = exp.s$Amount,
  N = exp.s$tot)


#boxplot, color by year of payment
b1<-ggplot(xy, aes(mydateYYYY, amount,
                   fill = start_year)) + 
  geom_boxplot() + 
  scale_fill_identity("legend") +
  theme_classic() +
  theme(axis.text.x=element_blank(),
        axis.title.x=element_blank())


#jitter plot, color by year of payment
b2<-ggplot(xy, aes(mydateYYYY, amount,
                   alpha=0.8,color=mydateYYYY, size = N))  + 
  geom_jitter() + 
  scale_color_identity() +
  theme_classic() +
  theme(legend.position="none") +
  theme(axis.text.x=element_blank(),
        axis.title.x=element_blank())


#jitter, color by contract start year
b3<-ggplot(xy, aes(mydateYYYY, amount,
                   alpha=0.9, color=start_year, size = N))  + 
  geom_jitter() + 
  scale_color_identity()  +
  theme_classic() +
  theme(legend.position="none") 


grid.arrange(b1, b2, b3, ncol=1)

enter image description here