【发布时间】:2020-11-02 05:38:51
【问题描述】:
我有一些数据 (x) 我想绘制为直方图。有两种样本类型 (s),每种样本都以两种不同的方式收集 (r)。
我想将它们绘制为由s 和r 填充的堆叠直方图——最好的方法是按照我的上一个示例对它们进行刻面,但我的空间有限。
我可以使用单个geom_histogram 绘制由s 填充的数据。我可以绘制两个geom_histograms 来绘制不同的r。我不知道如何制作不同的几何堆栈。我还没弄清楚如何填写它们,但ggnewscale 可能是一个选项。
我想选择填充,例如(例如)s == 红色、蓝色和r == 浅色、深色以及相应的s 颜色。
有什么建议吗?
library(tidyverse)
library(tibble)
x <- c(0,0,0,0,0,1,1,1,1,-1,-1,-1,-1,2,2,2,-2,-2,-2,3,3,-3,-3,4,-4, 8,8,8,8,8,9,9,9,9,9,7,7,7,10,10,10,6,6,6,11,11,5,5,12,4)
r <- as.factor(c(1,2,2,2,1,1,2,2,2, 1, 1, 2, 2,2,2,2, 1, 1, 2,2,2, 2, 2,2, 2, 1,1,2,2,2,1,1,1,2,1,1,2,2, 1, 2, 2,2,2,2, 2, 1,1,2, 1,1))
s <- c(rep.int("a", 25), rep.int("b", 25))
figsd <- tibble(x,r,s)
figsd %>%
ggplot(aes(x=x)) +
geom_histogram(aes(fill = s), binwidth = 1, position = "stack") +
coord_cartesian(ylim = c(0,5))
figsd %>%
ggplot(aes(x=x)) +
geom_histogram(data = . %>% filter(r == 1), aes(fill = s), binwidth = 1,alpha = 0.5, position = "stack") +
geom_histogram(data = . %>% filter(r != 1), aes(fill = s), binwidth = 1,alpha = 0.5, position = "stack") +
coord_cartesian(ylim = c(0,5))
figsd %>%
ggplot(aes(x=x)) +
geom_histogram(aes(fill = r), binwidth = 1,position = "stack") +
coord_cartesian(ylim = c(0,5)) +
facet_grid(s ~ .)
由reprex package (v0.3.0) 于 2020 年 11 月 2 日创建
【问题讨论】:
-
您可以使用交互:
ggplot(figsd, aes(x)) + geom_histogram(aes(fill = interaction(r, s)), binwidth = 1, position = "stack") + scale_fill_manual(values = c('1.a' = 'lightblue', '1.b' = 'darkblue', '2.a' = 'pink', '2.b' = 'darkred')) -
@alistaire 这正是我想要的。
interaction对我来说是一个新功能。谢谢。如果您想将其添加为答案,我会接受。