如何根据精确的截止点对ggplot直方图进行不同的着色? [英] How to color a ggplot histogram differently based on precise cut off points?

查看:33
本文介绍了如何根据精确的截止点对ggplot直方图进行不同的着色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to color a ggplot histogram differently based on precise boundaries along the x axis. However, the colors are not accurate because a bin that contains values from both colors will show up as a mixed color bin split up horizontally. Example minimal code and problem chart below.

我想按颜色垂直分割垃圾箱.因此,截止线左侧的所有值都是一种颜色,截止线右侧的所有值都是另一种颜色.

I would like to split the bin by color vertically. So that all values to the left of the cutoff line are one color and all values to the right of the cutoff line are the other color.

我该怎么做?

我认为geom_density不会出现此问题,但是我更喜欢使用geom_histogram而不是geom_density,因为直方图会在y轴上显示实际计数.

I think geom_density would not have this problem, but I would prefer to use geom_histogram instead of geom_density because the histogram shows actual counts on the y axis.

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 (边界)参数在我只有一个截止点时效果很好,但在我有以下两个截止点时则无效

The boundary argument works well when I have just one cutoff point, but it doesn't work when I have two cutoff points like below

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中指定bin-break.因此,我们首先创建一个间隔均匀的bin向量,并为其添加一些截止点:

Maybe this'll work for you. You can specify the bin-breaks in geom_histogram. So we first create an evenly spaced bin-vector and add some cutoff points to it:

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")

这篇关于如何根据精确的截止点对ggplot直方图进行不同的着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆