r - 如何将 geom_text 颜色映射到变量

标签 r ggplot2 colors geom-text

对于条形图,我想按自定义顺序垂直堆叠条形组件。在下面的示例中,控制堆叠顺序的变量是“mechanism”。预期的堆叠顺序既不是字母顺序,也不是数据帧行的排序顺序。并非所有酒吧都有所有机制。我手动设置序列并将该序列用作因子的水平。完全缺失的因子级别没有得到正确处理,对此解决方案将受到欢迎,但我可以解决这个问题。

为了添加指示每个分量大小的文本标签,我计算标签的 y 高度值并添加 geom_text。我希望文本的颜色与条形组件的颜色形成一致的对比:蓝色条形组件上的白色文本等。因此,我将 geom_text 的颜色分配给与 geom_bar 的填充相同的变量。但背景和文本的预期颜色配对并不保持匹配。请出主意?? (感谢编辑插入了乱七八糟的图的图片。)

期望的结果是每个机制为“热”的条形组件都将用黑色文本注释红色填充。每个机制为“城市”的组件都会有 tan4 填充,并用 grey50 文本注释。

我还尝试分配颜色而不将映射变量变成因子(示例选项 1),如 geom_text() & color gradient 所示.

library(ggplot2)
m.data <- data.frame(m.model = factor(c(1, 1, 2, 2, 4)),
   mechanism = c("urban", "hot", "hot", "urban", "urban"),
   bar.height = 1:5,
   y.for.text = c(.5, 2, 1.5, 5, 2.5))
mechanism.order <- c("hot", "dry", "urban")
mechanism.colors <- c("red", "blue", "tan4")
text.colors <- c("black", "white", "grey50")

m.map <- ggplot() +
   geom_bar(data = m.data, aes(x = m.model, y = bar.height, 
      fill = factor(mechanism, levels = mechanism.order)), 
      stat = "identity") +
   scale_fill_manual(values = mechanism.colors) +
   scale_color_manual(values = text.colors) 

# option 1:
m.map +    
   geom_text(data = m.data, aes(x = m.model, y = y.for.text,
      color = mechanism, label = bar.height)) 
   
# option 2:
m.map +    
   geom_text(data = m.data, aes(x = m.model, y = y.for.text,
      color = factor(mechanism, levels = mechanism.order), 
      label = bar.height))

最佳答案

要明确颜色,请将它们作为命名向量传递。

这里还有其他几点:

  1. 带有 stat = "identity"geom_bar 只是 geom_col 的长写方式
  2. 您不需要手动编码文本的 y 位置。只需在 geom_text 内使用 position_stack(vjust = 0.5) 即可获得中央条形标签
  3. 如果您的图层都使用相同的数据和 x、y 变量,请通过初始 ggplot 调用传递它们,并让图层继承它们
mechanism.colors <- c(hot = "red", dry = "blue", urban = "tan4")
text.colors <- c(hot = "black", dry = "white", urban = "gray50")

ggplot(data = m.data, aes(x = m.model, y = bar.height)) +
   geom_col(aes( fill = factor(mechanism, levels = mechanism.order))) +
   geom_text(aes(label = bar.height, color = mechanism),
             position = position_stack(vjust = 0.5), size = 8) +
   scale_fill_manual(values = mechanism.colors) +
   scale_color_manual(values = text.colors) +
   labs(fill = "mechanism") +
   guides(color = guide_none())

enter image description here

关于r - 如何将 geom_text 颜色映射到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71548629/

相关文章:

r - 如何添加 4 个组以制作具有均值线段的分类散点图?

r - ggplot2 中的透明 mask

r - 如何在多列上拆分kable?

r - randomForests 包中的 `LocalImp` 参数到底有什么作用?

r - GGlot2 Boxplot 只显示平线

javascript - 为输入范围生成红色和绿色之间的颜色

java - 使用 ImageIO.write 将 BufferedImage 保存为 PNG 文件后,颜色发生奇怪变化

r - 滚动窗口后创建预测矩阵

r - 用新数据框中的数据插入 NA

css - 使用 bootstrap 更改导航栏上文本的颜色