Reputation: 103
I want to draw a stack chart in R : My data set is as follows called df:
df <- structure(list(id = c("A","B"),
x1 = c(10,30),
x2 = c(20,40),
x3 = c(70,30)), row.names = 1:2,
class = "data.frame")
df<- melt(df, id.vars = "id")
library(ggplot2)
ggplot(data = df, aes(x = variable, y = value, fill =id)) +
geom_bar(stat = "identity") +
xlab("\nCategory") +
ylab("Percentage\n") +
guides(fill = FALSE) +
theme_bw()
The out put is not the one that I want,
I want to to see id in the x axis and x1,x2,x3 in the stacked column.
Upvotes: 0
Views: 69
Reputation: 726
ggplot's x
always specifies the x-axis, fill
the variable you want to categorize your data by. So to create your desired plot, the code is:
library(reshape2) ## for melt()
library(ggplot2)
df<- melt(n_df, id.vars = "id")
ggplot(data = n_df, aes(x = id, y = value, fill =variable)) +
geom_bar(stat = "identity") +
xlab("\nCategory") +
ylab("Percentage\n") +
guides(fill = FALSE) +
theme_bw()
If you want to have the legend show up, you have to guides(fill = TRUE)
:
Upvotes: 4