Reputation: 453
I am trying to plot a stacked bar chart with multiple facets using the code below:
dat <- read.csv(file="./fig1.csv", header=TRUE)
dat2 <- melt(dat, id.var = "id")
ggplot(dat2, aes(x=id, y=value, fill = variable)) +
geom_bar(stat="identity") +
facet_grid(. ~ col1) +
geom_col(position = position_stack(reverse = TRUE))
and here is a minimized example of how my data looks like:
id col1 col2 col3 col4 col5
1 1 0.2 0.1 0.1 0.1
2 1 0.2 0.1 0.2 0.1
3 1 0.2 0.2 0.2 0.1
4 2 0.1 0.1 0.2 0.1
5 2 0.1 0.1 0.1 0.2
However, I keep getting the error below. I think the problem is coming from facet_grid(. ~ col1)
and more specifically using col1
.
Error in combine_vars(data, params$plot_env, cols, drop = params$drop) :
At least one layer must contain all variables used for facetting
Does anyone have any idea how I can fix that?
Upvotes: 0
Views: 257
Reputation: 708
The col1
is not included as variable in the melt
function, so it will be melted together with the rest of columns. Just include col1
as variable in the melt
function.
dat2 <- melt(dat, id.var=c("id", "col1"))
Upvotes: 1