small_lebowski
small_lebowski

Reputation: 773

ggplot: Avoiding adding up factor variable in x-axis

I want to avoid adding up factor variables in my plot. Let's consider this data,

aa <- c(10, 12, 23)
bb <- c("a", "b", "a")
dataf <- data.frame(aa, bb)

library(ggplot2)
gplot <- ggplot(data=dataf, aes(x=bb, y=aa))+geom_bar(stat="identity")
gplot

This code will generate the following barplot.

enter image description here

As you see, there are two bars and the value of the first bar in y-axis is 33 (i.e. 10+23). I want to avoid this addition. That means, I want to see three bars instead of two. How can I do this?

Upvotes: 0

Views: 46

Answers (1)

Jaap
Jaap

Reputation: 83255

You can create a new column which identifies the unique values within each group:

dataf$rn <- ave(dataf$aa, dataf$bb, FUN = seq_len)

and then plot:

ggplot(data=dataf, aes(x=bb, y=aa, fill=factor(rn))) +
  geom_bar(stat="identity", position="dodge")

which gives:

enter image description here

However, as this does not give a nice plot with regard to the width of the bars, you can expand your dataframe as follows:

# expand the dataframe such that all the combinations of 'bb' and 'rn' are present
dfnew <- merge(expand.grid(bb=unique(dataf$bb), rn=unique(dataf$rn)), dataf, by = c('bb','rn'), all.x = TRUE)
# replace the NA's with zero's (not necessary)
dfnew[is.na(dfnew$aa),'aa'] <- 0

and then plot again:

ggplot(data=dfnew, aes(x=bb, y=aa, fill=factor(rn))) +
  geom_bar(stat="identity", position="dodge")

which gives:

enter image description here


In reponse to your comment, you could do:

dataf$rn2 <- 1:nrow(dataf)

ggplot(data=dataf, aes(x=factor(rn2), y=aa)) +
  geom_bar(stat="identity", position="dodge") +
  scale_x_discrete('', labels = dataf$bb)

which gives:

enter image description here

Upvotes: 3

Related Questions