0

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))
```
stefan
  • 90,330
  • 6
  • 25
  • 51
  • 1
    Can you make your example reproducible? You can provide your data by using `dput(Hospital)` or `dput(head(Hospital, n = 50))` if your original dataset is very large. – jrcalabrese Oct 24 '22 at 16:13
  • What do you mean by reproducible? Does this effect the colour? Or can the function of coloring the bars be changed? – Harry Plotter Oct 24 '22 at 16:16
  • 1
    Reproducible means that other people on StackOverflow can run your code and reproduce the issue you are facing. See more here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – jrcalabrese Oct 24 '22 at 16:22
  • Oh thanks! Ill post some data in the Post in a few seconds – Harry Plotter Oct 24 '22 at 16:25

1 Answers1

1

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

zephryl
  • 14,633
  • 3
  • 11
  • 30