我有一个更大的数据集,类似于以下内容:
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()
如何通过对比来改变颜色而不是创建适当的渐变?
最佳答案
你可以这样做
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))
如果您有很多人或回合,您可能需要使用 colorRamp
或 rgb
以编程方式设置颜色。
编辑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/