anderwyang
anderwyang

Reputation: 2411

In ggplot2/geom_density, how to fill densiyt area with differenc colors

In ggplot2/geom_density, i want to fill the area of wt >4 with 'YELLOW', but it's failed (some area not in >4 ,the fill color is yellow too. as attached image). Someon can help ? Thanks!

library(tidyverse)
mtcars %>% ggplot(aes(x=wt))+
  geom_density(aes(fill=if_else(wt<4,'red','yellow')))

enter image description here

Upvotes: 0

Views: 898

Answers (1)

Tech Commodities
Tech Commodities

Reputation: 1959

Density graphs show a distribution and so add tails. This makes it looks like the area below 4 is yellow. How about using a histogram, that doesn't add them?

For comparison,

library(tidyverse)

mtcars %>% ggplot(aes(x=wt)) +
  geom_histogram(aes(fill=if_else(wt < 4,'darkred','blue')), bins = 50) +
  geom_density(aes(fill=if_else(wt < 4,'red','yellow')), alpha = 0.6) +
  scale_colour_identity() +
  scale_fill_identity()

enter image description here

Upvotes: 1

Related Questions