Cenoc
Cenoc

Reputation: 11682

Barplots for all levels (even those with no values) in R

I'm graphing values associated with a range of factors I got from cut:

         a   b
1  (25,30]  10
2  (30,35] 313
3  (35,40] 904
4  (40,45] 809
5  (45,50] 608
6  (50,55] 514
7  (55,60] 227
8  (60,65] 323
9  (65,70]  23
10 (70,75]   5
11 (75,80]   1

I graph it with:

plt_tmp = barplot(agg$b)
axis(1, agg$a, at=plt_tmp,las=2) 

This would be fine, but the levels are actually (ie levels(agg$a)):

[1] "(0,5]"    "(5,10]"   "(10,15]"  "(15,20]"  "(20,25]"  "(25,30]"  "(30,35]"  "(35,40]"  "(40,45]" 
[10] "(45,50]"  "(50,55]"  "(55,60]"  "(60,65]"  "(65,70]"  "(70,75]"  "(75,80]"  "(80,85]"  "(85,90]" 
[19] "(90,95]"  "(95,100]"

And I was hoping I could graph all of them, including the missing ones, as 0 values. How would I go about doing this? Any help would be very much appreciated!

Upvotes: 2

Views: 59

Answers (2)

MarkusN
MarkusN

Reputation: 3223

Use package ggplot2 for your barchart. With scale option you can define wether unused levels are plotted or not:

library(ggplot2)
ggplot(agg, aes(x=a, y=b)) +
  geom_bar(stat="identity") +
  scale_x_discrete(drop=FALSE)

Upvotes: 1

thelatemail
thelatemail

Reputation: 93938

You need to merge all your levels back against your base data, and then pass that data to barplot. With a simplified example:

agg <- data.frame(a=factor(c(1,2,4), levels=1:5), b=c(10,1,20))
with(merge(agg, list(a=levels(agg$a)), all=TRUE), barplot(b, names.arg=a) )

Upvotes: 1

Related Questions