【问题标题】:How to manually fill colors in a ggplot2 histogram如何在 ggplot2 直方图中手动填充颜色
【发布时间】:2012-04-18 11:13:39
【问题描述】:

我正在生成一个直方图,我想用特定颜色为某些组着色。这是我的直方图:

我有 14 组,我想将前 7 组涂成红色,后 4 组涂成蓝色,最后 3 组涂成橙色。我怎样才能在ggplot中做到这一点?谢谢。

【问题讨论】:

  • 我假设您的意思是条形图,而不是直方图?有(大)差异。
  • 数据是不连续数据的频率图。我使用geom_histogram 绘制它。我不确定这是否构成“条形图”或“离散直方图”。
  • 好的。在这种情况下,我可能只使用 geom_bar 。然后你只需要在你的数据框中定义你想要的颜色分组的分组变量,然后将它映射到fill?geom_bar中有一些例子。
  • 谢谢,我会使用geom_bar。我认为可能有一种方法可以使用 geom_histogram 而无需定义颜色分组。
  • 如果您发布一个可重现的小示例,我们可以提供更具体的建议。

标签: r ggplot2


【解决方案1】:

更新版本

无需指定分组列,ggplot 命令更简洁。

library(ggplot2)
set.seed(1234)

# Data generating block
df <- data.frame(x=sample(1:14, 1000, replace=T))
# Colors
colors <- c(rep("red",7), rep("blue",4), rep("orange",3))

ggplot(df, aes(x=x)) +
  geom_histogram(fill=colors) +
  scale_x_discrete(limits=1:14)

旧版本

library(ggplot2)

# 
# Data generating block
#
df <- data.frame(x=sample(c(1:14), 1000, replace=TRUE))
df$group <- ifelse(df$x<=7, 1, ifelse(df$x<=11, 2, 3))

#
# Plotting
#
ggplot(df, aes(x=x)) +
  geom_histogram(data=subset(df,group==1), fill="red") +
  geom_histogram(data=subset(df,group==2), fill="blue") +
  geom_histogram(data=subset(df,group==3), fill="orange") +
  scale_x_discrete(breaks=df$x, labels=df$x)

【讨论】:

  • 我发现geom_histogram(fill=colors) 方法是处理累积直方图aes(y=cumsum(..count../sum(..count..))) 的唯一方法,因为在aes 内设置填充会导致组堆叠。更简单的stat_ecdf 方法对我不起作用,因为它不采用breaks 选项。最后,只有这种方法有效。
  • 我不能用 ggplot2 3.3.2 重现这个?我收到Error: StatBin requires a continuous x variable: the x variable is discrete. 谢谢!
猜你喜欢
  • 2011-02-02
  • 2015-04-04
  • 2017-03-10
  • 2018-12-12
  • 1970-01-01
  • 2019-10-31
  • 2013-08-26
  • 2016-12-11
  • 2022-01-17
相关资源
最近更新 更多