首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ggplot2中不同叠加颜色的对比分析

ggplot2中不同叠加颜色的对比分析
EN

Stack Overflow用户
提问于 2018-02-09 23:05:42
回答 2查看 506关注 0票数 2

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

代码语言:javascript
复制
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按轮变化:

代码语言:javascript
复制
library(ggplot2)
ggplot(data = example,
       aes(x = reorder(person, score),
           y = score,
           fill = factor(person),
           alpha = as.integer(round))) + 
  geom_col()

如何通过对比改变颜色来创建一个适当的渐变呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-02-09 23:13:06

你可以直接做

代码语言:javascript
复制
ggplot(data = example, aes(x = reorder(person, score), y = score, 
  fill = interaction(person, as.integer(round)))) + geom_col()

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

编辑

简单的例子是:

代码语言:javascript
复制
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

或者使用半透明的白色列来攻击它:

代码语言:javascript
复制
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))
票数 2
EN

Stack Overflow用户

发布于 2018-02-10 18:54:29

这里的诀窍(受@mikeck的启发)是在原始透明度之下创建坚实的颜色条:

代码语言:javascript
复制
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))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48715394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档