具有嵌套分类变量和 R 中纹理填充的堆积条形图

Stacked bar plot with nested categorical variables and textured fill in R

我正在尝试创建一个包含三个分类变量和一个离散变量的堆积条形图,其中一个分类变量“嵌套”在另一个分类变量中。 “嵌套”分类变量将通过颜色可视化,“嵌套”分类变量将通过不同的纹理(散列线、点等)可视化。结果看起来像这里的图像:https://i.stack.imgur.com/vVm9q.jpg

我在 R 中遇到了 2 个主要挑战:1) 将一个分类变量嵌套在另一个分类变量中,2) 用纹理符号化类别。我发现将一个分类变量“嵌套”在另一个分类变量中的最接近的解决方案是下面的脚本。但是,我希望使用 ggplot 而非轮廓颜色来区分“性别”类别。我还希望在 x 轴而不是 y 轴上有离散变量。 This question 显示“gridSVG”包可能有用,但我不确定如何将其与 ggplot 合并。

# This  sample dataset is taken from 
library(ggplot2)
library(tibble)

df <- tibble(
  mea = rep(c("PO_P", "Melaniz"), each = 6),
  tre = rep(c("a", "a", "b", "b", "c", "c"), 2),
  sex = rep(c("Male", "Female"), 6),
  len = c(10.66154, 10.58077, 10.29200, 10.60000, 10.28519, 10.65185,
          11.47857, 11.71538, 11.70833, 11.50000, 11.62143, 11.89231)
)

ggplot(df, aes(x = factor(mea), y = len, color = sex, fill = tre)) + 
  geom_bar(stat = "identity", size = 2)

reprex package (v0.3.0)

于 2019-09-04 创建

ggplot 没有纹理选项,但您仍然可以使用一些代码密集型选项(一些有用的链接 here)获得您想要的东西。在我看来,这太麻烦了,我更喜欢对图进行分面并比较结果(使用 fill = tre 并添加 facet_wrap(~sex) 或反之,具体取决于对您更有意义的内容)。

您可以使用 ggtextures 包执行此操作。但是,您将需要可以平铺的适当纹理图像。创建此类图像超出了此答案的范围。我在这里使用简单的动物图标。

library(ggplot2)
library(tibble)
library(magick)
#> Linking to ImageMagick 6.9.9.39
#> Enabled features: cairo, fontconfig, freetype, lcms, pango, rsvg, webp
#> Disabled features: fftw, ghostscript, x11
library(ggtextures) # devtools::install_github("clauswilke/ggtextures")

textures = list(
  Male = image_read_svg("http://steveharoz.com/research/isotype/icons/horse.svg"),
  Female = image_read_svg("http://steveharoz.com/research/isotype/icons/fish.svg")
)

df <- tibble(
  mea = rep(c("PO_P", "Melaniz"), each = 6),
  tre = rep(c("a", "a", "b", "b", "c", "c"), 2),
  sex = rep(c("Male", "Female"), 6),
  len = c(10.66154, 10.58077, 10.29200, 10.60000, 10.28519, 10.65185,
          11.47857, 11.71538, 11.70833, 11.50000, 11.62143, 11.89231)
)

ggplot(df) +
  aes(
    x = mea, y = len, image = sex, fill = tre,
    group = interaction(sex, tre) # determines which variable should be stacked first, sex or tre
  ) + 
  geom_textured_bar(
    stat = "identity",
    img_width = unit(20, "pt") # adjust for appropriate scaling of textures, or remove
  ) +
  scale_image_manual(values = textures) +
  coord_flip() +
  theme(legend.position = "bottom")

reprex package (v0.3.0)

于 2019-09-04 创建