具有多个方面的堆积条形图
Stacked bar chart with multiple facets
我正在尝试使用以下代码绘制具有多个方面的堆叠条形图:
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))
这里是我的数据的最小化示例:
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
但是,我不断收到以下错误。我认为问题出在 facet_grid(. ~ col1)
并且更具体地说是使用 col1
.
Error in combine_vars(data, params$plot_env, cols, drop = params$drop) :
At least one layer must contain all variables used for facetting
有人知道我该如何解决这个问题吗?
col1
未作为变量包含在 melt
函数中,因此它将与其余列融合在一起。只需将 col1
作为变量包含在 melt
函数中。
dat2 <- melt(dat, id.var=c("id", "col1"))
我正在尝试使用以下代码绘制具有多个方面的堆叠条形图:
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))
这里是我的数据的最小化示例:
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
但是,我不断收到以下错误。我认为问题出在 facet_grid(. ~ col1)
并且更具体地说是使用 col1
.
Error in combine_vars(data, params$plot_env, cols, drop = params$drop) :
At least one layer must contain all variables used for facetting
有人知道我该如何解决这个问题吗?
col1
未作为变量包含在 melt
函数中,因此它将与其余列融合在一起。只需将 col1
作为变量包含在 melt
函数中。
dat2 <- melt(dat, id.var=c("id", "col1"))