2015-10-27 111 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