如何基于精确的截止点对ggplot直方图进行不同的着色?

时间:2019-04-17 07:09:14

标签: r ggplot2

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

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

我该怎么做?

我认为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")

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:2)

也许这对您有用。您可以在geom_histogram中指定bin-break。因此,我们首先创建一个间隔均匀的bin向量,并向其添加一些截止点:

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

enter image description here