Nick
Nick

Reputation: 9051

How to plot multicolum in ggplot2?

I just came to R from Excel, and was thrilled by the elegance of chart quality of ggplot2. Since they are different tools, thus have different way of doing things. I have to train my brain to think in the R (ggplot2) way.

I would like to know, how to plot multicolumn data in ggplot2. I'd like take the following data as example:

State           Quarter 1   Quarter 2   Quarter 3   Total
Connecticut     385         410         521         1,316
Pennsylvania    545         416         598         1,559
Delaware        506         515         731         1,752
New Jersey      591         781         617         1,989
Maryland        946         436         895         2,277
Vermont         945         816         895         2,656
New York        910         867         946         2,723

Total           4,828       4,241       5,203       14,272

Question:

  1. I can plot each Quarter data to one barplot, how to plot all the Quarters at the same chart?
  2. This might be quite the Excel way, is there any better way to represent these data in R?

Upvotes: 1

Views: 163

Answers (2)

Nishanth
Nishanth

Reputation: 7130

As suggested in the comment, first melt the data frame:

require(reshape2)
require(ggplot2)

data = read.table(text="
State,   Quarter1,   Quarter2,   Quarter3,   Total
Connecticut,     385,         410,         521,         1316
Pennsylvania,    545,         416,         598,         1559
Delaware,        506,         515,         731,         1752
New Jersey,      591,         781,         617,         1989
Maryland,        946,         436,         895,        2277
Vermont,         945,         816,         895,         2656
New York,        910,         867,         946,         2723
Total,           4828,       4241,       5203,       14272",header=T,sep=',')

data.new <- melt(head(data,-1))

Now for stacked bar plot:

ggplot(head(data.new,-1), aes(State,value,fill=variable)) + geom_bar(position="dodge")

enter image description here

For side-by-side bar plot:

ggplot(head(data.new,-1), aes(State,value,fill=variable)) + geom_bar()

enter image description here

Upvotes: 1

Michele
Michele

Reputation: 8753

df <- read.csv(text="State,Quarter1,Quarter2,Quarter3,Total
Connecticut,385, 410, 521, 1316
Pennsylvania, 545, 416, 598, 1559
Delaware,506, 515, 731, 1752
New Jersey,591, 781, 617, 1989
Maryland,946, 436, 895, 2277
Vermont, 945, 816, 895, 2656
New York,910, 867, 946, 2723
", header=T)

library(reshape2)

df <- melt(df, variable.name="Quarter")

library(ggplot2)

ggplot(df[df$Quarter != "Total",]) + 
geom_bar(aes(State, value, fill = Quarter), stat="identity")

this creates the following chart:

enter image description here

Upvotes: 1

Related Questions