我有一个从1984年到现在的美国车辆燃油经济性的数据集。以下是我正在使用的数据框的摘要:
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中创建的图,如下所示:here 但是,如果使用ggplot进行复制很难,那么如果avg_city_MPG列位于avg_highway_MPG列的旁边则可以。
这是我到目前为止编写的剧情剧本。
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()
)
然而,所有这些产生的是第一层的条形图,然后只显示第二层的蓝线。
感谢您的帮助!
答案 0 :(得分: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)
比你可以玩颜色等