ChrisG
ChrisG

Reputation: 343

Stacked Barplot in R with ggplot2

I have got a question about creating a stacked barplot in R with ggplot2. What I want to create is a stacked bar plot in which every bar is placed "on top" of the other.

x = c(100,200,400,600,800,1000,1250,1500)
y1 = c(1,2,3,4,5,6,7,8)
y2 = c(8,7,6,5,4,3,2,1)
data <- data.frame(x,y1,y2)
ggplot(data, aes(x, y1,label=x)) + 
  geom_bar(stat="identity", fill="blue", position="stack") +     
  geom_bar(stat="identity",aes(x, y2), fill="orange", position="stack")

What I get now are stacked bars. But for x = 100 I get one bar from 0 - 1 and a second from 0 - 8. But what I want to get is one from 0 - 1 and a second from 1 - 9.

Have you an idea how I can solve this problem (without summing up the inputs manually)?

Thanks for your help!

Upvotes: 0

Views: 955

Answers (2)

rnso
rnso

Reputation: 24535

Try:

ggplot(melt(data, id='x')) + geom_bar(aes(x=x, y=value, fill=variable), stat='identity')

enter image description here

Upvotes: 2

thothal
thothal

Reputation: 20329

How about:

df <- data.frame(x = c(x,x), y = c(y1, y2), grp = factor(rep(c("Grp 1", "Grp 2"), each = 8)))
ggplot(df, aes(x, y, fill = grp)) + geom_bar(stat = "identity", position="stack")

Use scale_fill_manualif you want to tweak the colors.

Upvotes: 0

Related Questions