phaser
phaser

Reputation: 625

ggplot2: change the order of bars so that bars with smaller values are on top of bars with larger values

Here is a sample of my data and graph:

m <- c("jun","jun","jul","aug","aug")
a <- c(1,10,2,10,2)
b <- c("x","y","x","x","y")

df <- data.frame(m,a,b)

ggplot(df,
       aes(x=m, y=a, fill=b)) + 
  geom_bar(stat="identity", position = "identity") 

enter image description here

I would like the x value of one to show up on the jun bar. I want the bars to be on top of one another not side by side.

I ended up using transparency. But I am still curious if their is another way to do it.

Upvotes: 1

Views: 354

Answers (2)

phaser
phaser

Reputation: 625

Using transparency gets what I want:

ggplot(df,
       aes(x=m, y=a, fill=b)) + 
  geom_bar(stat="identity", position = "identity", alpha=0.5) 

Upvotes: 0

F. Priv&#233;
F. Priv&#233;

Reputation: 11738

What I'd do:

ggplot(df, aes(x = m, y = a, fill = b)) + 
  geom_bar(stat = "identity", position = position_dodge(preserve = "single")) 

enter image description here

Make sure you have the latest version of ggplot2: devtools::install_github("tidyverse/ggplot2").

Upvotes: 1

Related Questions