我有一个类似于以下内容的更大数据集:
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()
如何通过对比改变颜色而不是创建一个合适的渐变?
答案 0 :(得分:2)
你可以做到
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))
答案 1 :(得分:1)
这里的诀窍(受@mikeck启发)是在原始透明度下创建纯色条:
ggplot(data = example, aes(x = reorder(person, score), y = score)) +
# Base bar color (black is another good color to try)
geom_col(fill = "white") +
# Overlay with the colored transparency
geom_col(aes(fill = factor(person), alpha = round))