Search code examples
rggplot2colorshistogram

Problem with colouring a GG Plot Histogram


I`ve got an issue with colouring a ggplot2 histogram.

R-Junk

ggplot(Hospital, aes(x=BodyTemperature)) +
  geom_histogram(aes(fill = factor(BodyTemperature))) +
  scale_x_continuous(breaks = seq(0, 100, by = 10)) +
  ylab("prevalence") + 
  xlab("BodyTemperature") +
  ggtitle("Temperature vs. prevalence")

So the histogram should plot the information (x-axis), that as higher the temperature gets, the worse it is. So for example „temperature“ at 36°C should be green, 38°C yellow, 40° red - going from left to right on the x-axis. Y-Axis should provide how often these temperatures ocures in the Patientdata of the Hospital. The Data "BodyTemperature" is a list of 200+ Data like: "35.3" or "37.4" etc.

How can this chunk be fixed to provide the color changes? For a non-ggplot version ive already written this r-junk positiv:

```{r, fig.width=8}
color1 <- rep(brewer.pal(1, "Greens"))
color2 <- rep("#57c4fa", 0)
color3 <- brewer.pal(8, "Reds")
hist(Hospital$BodyTemperature[-357],
  breaks = seq(from = 0, to = 100, by = 10),
  main = "Temperature vs. prevalence", 
  ylab = "prevalence",
  xlab = "Temperature", 
  col = c(color1, color2, color3))
```

Solution

  • The key is to make sure the bin intervals used for the fill scale match those used for the x axis. You can do this by setting the binwidth argument to geom_histogram(), and using ggplot2::cut_width() to break BodyTemperature into the same bins for the fill scale:

    set.seed(13)
    library(ggplot2)
    
    # example data
    Hospital <- data.frame(BodyTemperature = 36.5 + rchisq(100, 2))
    
    ggplot(Hospital, aes(BodyTemperature)) +
      geom_histogram(
        aes(fill = cut_width(BodyTemperature, width = 1)),
        binwidth = 1,
        show.legend = FALSE
      ) +
      scale_fill_brewer(palette = "RdYlGn", direction = -1) +
      labs(
        title = "Temperature vs. Prevalence",
        x = "Body Temperature (°C)", 
        y = "Prevalence"
      ) + 
      theme_minimal()
    

    Created on 2022-10-24 with reprex v2.0.2