通过对变量进行分组,在ggplot中对直方图进行着色

时间:2017-08-17 08:07:31

标签: r ggplot2

我认为这很容易,但不是那么容易。

我的代码中有一些直方图。他们可以按照标准的颜色主题没有问题,但是如果我想让他们按照调色板(对于例如带有不同组点的单个散点图工作正常),一切都会变得混乱。

红色进来的地方到了哪里?

此处的数据:https://pastebin.com/0p7SP005

library(ggplot2)
library(ggthemes)

ggplot(data = point_list, aes(x = lifetime,
                              y = ..density..)) +
    geom_histogram() +
    aes(fill = as.factor(cluster),
        col = "black") + 
    scale_x_continuous(expand = c(0,0)) +
    scale_y_continuous(expand = c(0,0)) +
    coord_cartesian(xlim = c(-2.6,50),
                    ylim = c(0,0.16)) +
    theme_tufte(base_size = 11, base_family = "Helvetica") +
    theme(axis.text = element_text(color = "black"),
          panel.border = element_rect(colour = "black", fill=NA, size=0.7),
          legend.position = "none") +
    facet_wrap(~cluster, scales = "free", ) +
    scale_color_brewer(palette = "Set1")

enter image description here

作为参考,Set1应如下所示: enter image description here

2 个答案:

答案 0 :(得分:3)

我将说明为什么酒吧的轮廓是红色的,因为其他一切已经被覆盖了。

在您的代码中,您在美学映射函数中有col = "black",这意味着颜色(用于轮廓)被映射到变量。在这种情况下,“黑色”将被解释为1级的因素。由于您的代码还包含scale_color_brewer(palette = "Set1"),因此生成的颜色是Set1调色板中的第一种颜色,即亮红色。

(实际的单词并不重要;如果你有col = "white"或类似的东西,它就没有任何区别。)

如果您选择了不同的调色板,轮廓颜色也会有所不同。例如:

ggplot(data = point_list, aes(x = lifetime,
                              y = ..density..)) +
  geom_histogram(size = 3) + # thicker outline to make the color more obvious
  aes(fill = as.factor(cluster),
      col = "black") + 
  scale_x_continuous(expand = c(0,0)) +
  scale_y_continuous(expand = c(0,0)) +
  coord_cartesian(xlim = c(-2.6,50),
                  ylim = c(0,0.16)) +
  # theme_tufte(base_size = 11, base_family = "Helvetica") + #commenting this out since I don't have this theme
  theme(axis.text = element_text(color = "black"),
        panel.border = element_rect(colour = "black", fill=NA, size=0.7),
        legend.position = "none") +
  facet_wrap(~cluster, scales = "free", ) +
  scale_color_brewer(palette = "Set2")

https://stackoverflow.com/a/36257493/5003342

Set2调色板中的第一种颜色是浅绿色(#66c2a5),这就是我们在这里看到的。

要获得黑色轮廓,请按照上面的loki example指定geom_histogram中的颜色,并确保这次在aes()之外执行此操作。 :)

答案 1 :(得分:2)

如果您想将红色更改为黑色,只需将geom_histogram行更改为:

geom_histogram(color = "black")

enter image description here