2015-10-27 110 views
0

我有從1984年到現在的美國車輛的燃油經濟性數據集。這裏是我處理的數據幀的總結:在ggplot2中創建條形圖,其中條形圖中的列並排排列

TRANY    avg_city_MPG avg_highway_MPG 
1 Automatic 3-spd  17.52586  21.74484 
2 Automatic 4-spd  15.96250  21.72190 
3 Automatic 5-spd  15.44277  21.64927 
4 Automatic 6-spd  16.67511  23.73770 
5 Automatic 6spd  21.00000  34.00000 
6 Automatic 7-spd  17.13578  24.47764 
7 Automatic 8-spd  16.69271  24.92708 
8 Automatic 9-spd  20.39623  28.90566 
9  Manual 3-spd  14.25974  16.94805 
10 Manual 4-spd  17.41470  21.82131 
11 Manual 5 spd  14.00000  14.00000 
12 Manual 5-spd  19.29711  25.73959 
13 Manual 6-spd  18.17111  26.03095 
14 Manual 7-spd  18.07143  25.92857 

我最終想要做的就是重新建立一個情節我的Tableau做,它看起來像這樣:Image of my Tableau plot I want to recreate 然而,如果它是太難如果avg_city_MPG列在avg_highway_MPG列旁邊,則可以使用ggplot正確地複製它。

這是我迄今爲止撰寫的情節劇本。

ggplot() + 
    coord_cartesian() + 
    scale_x_discrete() + 
    scale_y_continuous() + 
    #facet_wrap(~TRANY, ncol=1) + 
    labs(title='Average Highway MPG based on transmission ') + 
    labs(x=paste("Transmission"), y=paste("Average Highway MPG")) + 
    layer(data=bar_chart, 
     mapping=aes(x=TRANY, y=avg_highway_MPG), 
     stat="identity", 
     stat_params=list(), 
     geom="bar", 
     geom_params=list(colour="blue"), 
     position=position_dodge() 
) + 
    layer(data=bar_chart, 
     mapping=aes(x=TRANY, y=avg_city_MPG), 
     stat="identity", 
     stat_params=list(), 
     geom="bar", 
     geom_params=list(colour="blue"), 
     position=position_dodge() 
) 

然而,這一切產生的是第一層的條形圖,然後只顯示第二層的藍線。

謝謝你的幫助!

回答

2

試試這個

dfe <- read.table(header = T, stringsAsFactors = F, text = " id TRANY TRANY1    avg_city_MPG avg_highway_MPG 
      1 Automatic 3-spd  17.52586  21.74484 
      2 Automatic 4-spd  15.96250  21.72190 
      3 Automatic 5-spd  15.44277  21.64927 
      4 Automatic 6-spd  16.67511  23.73770 
      5 Automatic 6spd  21.00000  34.00000 
      6 Automatic 7-spd  17.13578  24.47764 
      7 Automatic 8-spd  16.69271  24.92708 
      8 Automatic 9-spd  20.39623  28.90566 
      9  Manual 3-spd  14.25974  16.94805 
      10 Manual 4-spd  17.41470  21.82131 
      11 Manual 5-spd  14.00000  14.00000 
      12 Manual 5-spd  19.29711  25.73959 
      13 Manual 6-spd  18.17111  26.03095 
      14 Manual 7-spd  18.07143  25.92857") 

head(dfe) 




dfe <- dfe %>% mutate(TRANY = paste(TRANY, TRANY1, sep = " ")) %>% select(-TRANY1, -id) 
library(reshape2) 
dfe <- melt(dfe, id.vars = c("TRANY")) 


ggplot(aes(x = TRANY, y = value), data = dfe) + geom_bar(stat = "identity") + coord_flip() + facet_wrap(~variable) 

enter image description here

比你可以用顏色ECT

+0

非常感謝你玩!這正是我需要它做的。 – Spencer