rlearner
rlearner

Reputation: 9

plotting 3 variables using barplot in r

I have an input table of the following :

    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

And I wish to plot this using barplot:

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

May I know how could I do that? I have not been able to plot what I wanted so far using 3 variables...

Pls help! thanks!

I've created an example of my desired image

Adding the dataframe code created by Akrun earlier (thanks 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))

Upvotes: 0

Views: 1574

Answers (2)

Hugh
Hugh

Reputation: 16090

Answering your question literally, I think you want width = value as one of the aesthetics.

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

However, I think a far more sensible option would be to use a tile:

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

Upvotes: 0

scoa
scoa

Reputation: 19867

Try something like this (providing d is your data.frame):

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

or

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

Upvotes: 2

Related Questions