r - ggplot2 中通过对比度改变堆叠颜色

标签 r ggplot2

我有一个更大的数据集,类似于以下内容:

example = data.frame(
  person = c(1,1,1, 2,2,2, 3,3,3),
  score =  c(5,1,2, 3,5,1, 1,2,2),
  round =  c(1,2,3, 1,2,3, 1,2,3)
)

我试图绘制它,以便每个人都有自己的颜色,并且堆栈中的每个条形都像渐变一样构建。我设法得到的最接近的结果是允许 alpha 每轮变化:

library(ggplot2)
ggplot(data = example,
       aes(x = reorder(person, score),
           y = score,
           fill = factor(person),
           alpha = as.integer(round))) + 
  geom_col()

如何通过对比来改变颜色而不是创建适当的渐变?

enter image description here

最佳答案

你可以这样做

ggplot(data = example, aes(x = reorder(person, score), y = score, 
  fill = interaction(person, as.integer(round)))) + geom_col()

然后使用scale_fill_manual定义颜色值来定义渐变。

编辑

举个简单的例子:

colornames = sort(levels(interaction(example$person, as.integer(example$round))))
colors = c(
  paste0("red", 1:3),
  paste0("green", 1:3),
  paste0("blue", 1:3)
)

ggplot(data = example, aes(x = reorder(person, score), y = score, 
  fill = interaction(person, as.integer(round)))) + geom_col() +
  scale_fill_manual(values = setNames(colors, colornames))

如果您有很多人或回合,您可能需要使用 colorRamprgb 以编程方式设置颜色。

编辑2

或者使用半透明的白色柱子来破解它:

ggplot(data = example, aes(x = reorder(person, score), y = score, fill = factor(person))) + 
  geom_col() + geom_col(aes(alpha = as.integer(round)), fill = "white") +
  scale_alpha(NULL, guide = FALSE, range = c(0, 0.4))

关于r - ggplot2 中通过对比度改变堆叠颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48715394/

相关文章:

regex - r + 搜索字符串并返回值

r - 列出文件时在文件类型后使用美元符号 '$'

r - R "undefined columns selected"中的错误

r - 在 R 中使用蒙特卡洛模拟股票价格

r - 如何使用 ggplot 和 dplyr 从函数中的 quosures 创建因子变量?

r - ggplot/mapping 美国县 — R 中的可视化形状问题

r - 将图例/文本表添加到具有多个图层的 ggmap

r - ggplot2 比例平方

r - 如何反转轴顺序并在 ggplot 中使用预定义的比例?

r - mtcars ggplot 不知道如何处理数字类