2017-06-20 26 views
0

我有汽車的數據框架(價格測量在n個品牌註冊年數的2個不同時期)。我想分析價格變化的動態,所以我試圖爲每個品牌創建一個圖表(x =年份,y =兩個價格系列)的圖表列表。R - ggplot - 適合大量的圖表到一個屏幕

# data frame example 

brand=sort(rep(paste(letters[1:26]),16)) 
data_date = rep(seq(as.Date("2017/5/1"), by = "month", length.out = 2),208) 
category = rep(c(1,2),208) 
cars = data.frame(brand, data_date, category) 
cars = cars[order(cars$brand, cars$data_date, cars$category),] 
year = rep(rep(seq(as.Date("2010/1/1"), by = "year", length.out = 8),2),26) 
cars = cbind(cars, year, price= abs(rnorm(416))*10) 
View(cars) 


我創建使用ggplot和facet_wrap和facet_grid圖表,但圖表是幾乎不可讀的。 我試圖使用包gridExtra和grid.arrange函數,但這給了我一個錯誤,我無法解決。 另一個替代性多槽不適用於R版本3.3.3

任何人都可以解釋爲什麼grid.arrange在這裏不起作用嗎?
(相同的圖表打印次數)
有沒有更好的方法來獲得所有的圖表在一個屏幕上?

有我的嘗試:

load(ggplot2) 

# plot 1 

ggplot(data=cars , aes(x=cars$year , y=cars$price, 
          group=interaction(cars$brand, cars$data_date), 
          fill=interaction(cars$brand, cars$data_date), 
          color =interaction(cars$brand, cars$data_date)))+ 
    geom_line()+ geom_point() + 
    #facet_grid(.~cars$brand) 
    facet_wrap(~cars$brand, ncol=2) 


# plot 2 using loop 

car_brands = levels(cars$brand) 
p_list=list(0) 

for (i in 1:26) { 

    plot_data = cars[(cars$brand==car_brands[i]),]  
    p1 = ggplot(data=plot_data , aes(x=plot_data$year , y=plot_data$price, 
           group=interaction(plot_data$brand, plot_data$data_date), 
           fill=interaction(plot_data$brand,plot_data$data_date), 
           color =interaction(plot_data$brand,plot_data$data_date)))+ 
    geom_line()+ geom_point() + 
    facet_grid(.~plot_data$brand)+ 
     ggtitle(car_brands[i]) 

    p_list[[i]] = p1 

    } 

library(gridExtra) 
grid.arrange(p_list, ncol=2) 

Error in gList(list(list(data = list(brand = c(1L, 1L, 1L, 1L, 1L, 1L, : 
    only 'grobs' allowed in "gList" 



UPDATE

grid.arrange(grobs=p_list, ncol=2) 

工作圍繞錯誤,但仍有兩個問題環路的方法:

1.圖表仍然很難讀取
2.相同的圖表正在打印次數(循環的問題是什麼?我不明白爲什麼它不工作)

有沒有更好的方法來創建此任務?

+1

我沒有看到與第一次運行的問題。只需移動或移除圖例或獲得更大的屏幕即可看到!而*更好的方式就是運行多個圖形,因爲您對一個屏幕有很多圖形。並使用* grobs * arg:'grid.arrange(grobs = p_list,ncol = 2)' – Parfait

+0

好的,這似乎工作,但圖表不能再次讀取,尤其是當我設置ncol = 1。無論如何強迫圖表達到一定的大小? – Michal

+0

@ Parfait循環方法重複相同的圖表。循環的問題是什麼? – Michal

回答

1

,而不是考慮by代替for循環,因爲它切片你的數據幀由指定因子(S)成dataframes列表任何需要的操作,如ggplot。又要考慮降低圖表的數量可讀性甚至調整的傳說和如下軸表明:

p_list <- by(cars, cars$brand, function(b) {  
    brand_date <- interaction(b$brand, b$data_date) 

    p <- ggplot(data=b, aes(x=b$year, y=b$price, 
        group = brand_date, 
        fill = brand_date, 
        color = brand_date)) + 
    geom_line() + geom_point() + 
    facet_grid(.~b$brand) + labs(x="Year", y="Price") + 
    theme(legend.position="bottom") + 
    ggtitle(max(as.character(b$brand))) 

}) 

# VERY LARGE PLOT 
grid.arrange(grobs=p_list, ncol=2) 

# FIRST 6 GRAPHS FOR BETTER READABILITY 
grid.arrange(grobs=p_list[1:6], ncol=2) 

Car Brands Multiple Plot Output

0

我發現錯誤在2循環的方法 aes_string()被要求的aes()