【问题标题】:How to color a ggplot histogram differently based on precise cut off points?如何根据精确的截止点对 ggplot 直方图进行不同的着色?
【发布时间】:2019-04-17 07:09:14
【问题描述】:

我正在尝试根据沿 x 轴的精确边界对 ggplot 直方图进行不同的着色。但是,颜色并不准确,因为包含两种颜色值的 bin 将显示为水平拆分的混合颜色 bin。下面的示例最小代码和问题图表。

我想按颜色垂直分割 bin。这样截止线左侧的所有值都是一种颜色,而截止线右侧的所有值都是另一种颜色。

我怎样才能做到这一点?

我认为 geom_density 不会有这个问题,但我更喜欢使用 geom_histogram 而不是 geom_density,因为直方图显示 y 轴上的实际计数。

cutoff_point <- 3.9
mtcars %>% 
  mutate(wt_color = ifelse(wt < cutoff_point, "red", "blue")) %>% 
  select(wt, wt_color) %>% 
  ggplot(aes(x=wt, fill = wt_color)) +
  geom_histogram(bins = 5) +
  geom_vline(xintercept=cutoff_point, colour="black")

boundary 参数在我只有一个分界点时效果很好,但在我有两个分界点时不起作用,如下所示

cutoff_point1 <- 2.5
cutoff_point2 <- 5.4

mtcars %>% 
  mutate(wt_color = case_when(
    wt < cutoff_point1 ~ "blue",
    wt > cutoff_point1 & wt < cutoff_point2 ~ "red",
    TRUE ~ "green"
    )) %>% 
  select(wt, wt_color) %>% 
  ggplot(aes(x=wt, fill = wt_color)) +
  geom_histogram(bins = 5, boundary=cutoff_point) +
  geom_vline(xintercept=cutoff_point, colour="black")

【问题讨论】:

  • 您可以为您的geom_histogram 提供boundary=cutoff_point。这将改变分箱,使一个边界正好在您的截止点
  • 啊,当我在这个例子中只有两个组时,这很有效,但在我的实际图表中,我有多个截止点,在这种情况下,它似乎没有做任何事情
  • 啊。是的。您只能指定一个截止点。那我得想点更复杂的事情了
  • 我会用另一个例子更新问题

标签: r ggplot2


【解决方案1】:

也许这对你有用。您可以在 geom_histogram 中指定 bin-breaks。所以我们首先创建一个均匀间隔的 bin-vector 并为其添加一些截止点:

n.bins <- 5 # number of bins
additional.cutoffs <- c(3.9, 2.9) # additional bins

bins <- seq(min(mtcars$wt), max(mtcars$wt), length.out = n.bins)    
bins <- c(bins, additional.cutoffs) %>% sort()

mtcars %>% 
  mutate(wt_color = ifelse(wt < cutoff_point, "red", "blue")) %>% 
  select(wt, wt_color) %>% 
  ggplot(aes(x=wt, fill = wt_color)) +
  geom_histogram(breaks = bins) +
  geom_vline(xintercept=additional.cutoffs, colour="black")

【讨论】:

  • 啊。我认为有一种方法可以添加多个休息时间,但我一生都记不起来了。很好的解决方案!
  • 太棒了!谢谢!
  • 这很好用,但是在我的数据集上,我意识到条形图被切碎并在截止点处变短。我问了另一个question here 展示了一个例子。知道如何解决吗?
猜你喜欢
  • 2018-10-04
  • 1970-01-01
  • 2012-09-23
  • 2012-08-06
  • 2015-10-09
  • 2020-08-15
  • 2013-06-16
  • 2021-09-05
  • 2014-11-25
相关资源
最近更新 更多