并排堆叠不同颜色的条形图
Side by side stacked barplots with different colors
我正在尝试创建一个具有两个并排堆叠条形图的图形,其中每个条形图具有不同的配色方案。这是一些模型代码:
prob.out = function(lam){
out1 = dpois(x = 0:3, lambda = lam)
return(c(1-sum(out1), sort(out1)))
}
Prob.out = Vectorize(prob.out, SIMPLIFY = "vector")
synth.data = data.frame(
year = rep(2019:2021, each = 10) %>% as.character(),
small.cat = rep(rep(c("a", "b"), each = 5), times = 3),
response.var = round(c(Prob.out(lam = c(1, .7, .9, .6, .8, .5)))*10000,0)
)
library(ggplot2)
ggplot(data = synth.data, aes(small.cat, y = response.var, color = response.var, fill = response.var)) +
geom_col(position = "fill") +
facet_wrap(~year)
有没有办法改变 small.cat 色标彼此独立?
我的目标是得到一个看起来像这样的图形:
实现您想要的结果的一个选项是 ggnewscale
包,它允许多个比例以获得相同的美感。要完成这项工作,您必须通过单独的 geom_col
:
为每个 small.cat
添加条形图
library(ggplot2)
library(ggnewscale)
ggplot(data = synth.data, aes(small.cat, y = response.var)) +
geom_col(data = subset(synth.data, small.cat == "a"), aes(color = response.var, fill = response.var), position = "fill") +
new_scale_fill() +
new_scale_color() +
geom_col(data = subset(synth.data, small.cat == "b"), aes(color = response.var, fill = response.var), position = "fill") +
scale_fill_gradient(low = "red", high = "darkred") +
scale_color_gradient(low = "red", high = "darkred") +
facet_wrap(~year)
我正在尝试创建一个具有两个并排堆叠条形图的图形,其中每个条形图具有不同的配色方案。这是一些模型代码:
prob.out = function(lam){
out1 = dpois(x = 0:3, lambda = lam)
return(c(1-sum(out1), sort(out1)))
}
Prob.out = Vectorize(prob.out, SIMPLIFY = "vector")
synth.data = data.frame(
year = rep(2019:2021, each = 10) %>% as.character(),
small.cat = rep(rep(c("a", "b"), each = 5), times = 3),
response.var = round(c(Prob.out(lam = c(1, .7, .9, .6, .8, .5)))*10000,0)
)
library(ggplot2)
ggplot(data = synth.data, aes(small.cat, y = response.var, color = response.var, fill = response.var)) +
geom_col(position = "fill") +
facet_wrap(~year)
有没有办法改变 small.cat 色标彼此独立?
我的目标是得到一个看起来像这样的图形:
实现您想要的结果的一个选项是 ggnewscale
包,它允许多个比例以获得相同的美感。要完成这项工作,您必须通过单独的 geom_col
:
small.cat
添加条形图
library(ggplot2)
library(ggnewscale)
ggplot(data = synth.data, aes(small.cat, y = response.var)) +
geom_col(data = subset(synth.data, small.cat == "a"), aes(color = response.var, fill = response.var), position = "fill") +
new_scale_fill() +
new_scale_color() +
geom_col(data = subset(synth.data, small.cat == "b"), aes(color = response.var, fill = response.var), position = "fill") +
scale_fill_gradient(low = "red", high = "darkred") +
scale_color_gradient(low = "red", high = "darkred") +
facet_wrap(~year)