使用r中的barplot绘制3个变量

时间:2015-05-23 08:05:19

标签: r bar-chart

我有一个以下输入表:

    city    district    shoptype    value
     A      A1           retail     1000
     A      A1        restaurant    200
     A      A2           retail    5000
     A      A2        restaurant    600
     B      A1           retail    2000
     B      A1        restaurant   3000
     B      A2            retail    400
     B      A2        restaurant    500

我希望用barplot绘制这个:

  X axis: City and District, Y axis: shoptype, size of bar: value

我可以知道我该怎么办?到目前为止,我还无法使用3个变量来绘制我想要的内容...

请帮忙! 谢谢!

I've created an example of my desired image

添加之前由Akrun创建的数据帧代码(感谢Akrun)

df1 <- structure(list(city = c("A", "A", "A", "A", "B", "B", "B", "B"), 
   district = c("A1", "A1", "A2", "A2", "A1", "A1", "A2", "A2"), 
   shoptype = c("retail", "restaurant", "retail", "restaurant", "retail", "restaurant", "retail", "restaurant"), 
   value = c(1000L, 200L, 5000L, 600L, 2000L, 3000L, 400L, 500L)), 
  .Names = c("city", "district", "shoptype", "value"), 
  class = "data.frame", row.names = c(NA, -8L))

2 个答案:

答案 0 :(得分:2)

尝试这样的事情(假设d是你的data.frame):

library(ggplot2)
ggplot(data=d,aes(x=paste(city,district),y=value,fill=shoptype)) +
  geom_bar(stat="identity",position="dodge")

gplot(data=d,aes(x=district,y=value,fill=shoptype)) +
  geom_bar(stat="identity",position="dodge") +
  facet_grid(. ~ city)

答案 1 :(得分:0)

从字面上回答你的问题,我认为你希望width = value成为美学之一。

ggplot(df1, aes(x = paste0(city, district), y = shoptype, fill = paste0(city, district), width = value)) + 
geom_bar(stat = "identity", position = "dodge")

但是,我认为更明智的选择是使用瓷砖:

ggplot(df1,
       aes(x = paste0(city, district), 
           y = shoptype, 
           fill = paste0(city, district), 
           width = value)) + 
  geom_bar(stat = "identity", position = "dodge")

enter image description here