为什么ggplot在指定其他颜色时使用默认颜色?

时间:2015-02-19 15:09:03

标签: r ggplot2 histogram

我试图让ggplot2将直方图的一行显示为与其余颜色不同的颜色。在这方面我取得了成功;但是,当指定了不同的集合时,ggplot使用默认颜色。我确信我的代码中有错误,但我无法确定它的位置。数据和代码如下:

创建数据

library(ggplot2)
set.seed(71185)
dist.x <- as.data.frame(round(runif(100000, min= 1.275, max= 1.725), digits=2))
colnames(dist.x) <- 'sim_con'

开始直方图

ggplot(dist.x, aes(x = sim_con)) +
geom_histogram(colour = "black", aes(fill = ifelse(dist.x$sim_con==1.55, "darkgreen", "firebrick")), binwidth = .01) +
theme(legend.position="none")

结果如下图所示: enter image description here

我不想使用默认颜色,而是想使用&#39; darkgreen&#39;和&#39;耐火砖&#39;。代码中的错误在哪里?感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:5)

你真是太近了!

在上面的代码中,ggplot将您的填充解释为数据集中的变量 - 因子darkgreen和因子firebrick - 并且无法知道这些标签是颜色,而不是动物物种的名称。

如果您将scale_fill_identity()添加到绘图的末尾,如下所示,它会将这些字符串解释为颜色(身份),而不是数据的功能。

这种方法的一个好处vs @ marat上面的优秀答案:如果你有一个复杂的情节(例如,使用geom_segment(),每个观察的起始值和结束值)并且你想要应用两个填充您可以在数据处理步骤中对数据进行缩放(起始值的一个刻度和结束值的不同刻度),然后使用scale_fill_identity()相应地为每个观察颜色着色。

ggplot(
  data=dist.x,
  aes(
    x = sim_con,
    fill = ifelse(dist.x$sim_con==1.55, "darkgreen", "firebrick")
  )
) +
geom_histogram(
  colour = "black",
  binwidth = .01
) +
theme(legend.position="none") +
scale_fill_identity()

答案 1 :(得分:3)

我认为你不能在aes中明确设置颜色;您需要在scale_fill_manual中执行此操作,如下例所示:

ggplot(dist.x, aes(x = sim_con)) +
  geom_histogram(colour = "black", binwidth = .01,aes(fill=(sim_con==1.55))) + 
  scale_fill_manual(values=c('TRUE'='darkgreen','FALSE'='firebrick')) +
  theme(legend.position="none")

enter image description here