1

I am visualizing the relationship between two variables with a histogram. The bins I used are filled with a colour gradient, to show the development of this numerical variable over the bins. To make it a bit more clear to the eye, I would like to add the mean'fill' value for that bin, e.g., above the bar. My code is below and I included a table (with the bin means drawn written on top by hand). How could I edit my code so the means are calculated and displayed like in the picture?

p <- df2 %>% 
  mutate(dist2init = cut(x      = dist2init, 
                   breaks = hist(dist2init, breaks = 0:1500 * 100, plot = FALSE)$breaks,
                   labels = hist(dist2init, breaks = 0:1500 * 100, plot = FALSE)$mids)) %>%
  group_by(dist2init) %>%
  summarize(n = n(), building_dissimilarity = mean(building_dissimilarity)) %>%
  ggplot(aes(x = as.numeric(as.character(dist2init)), y = n, fill = building_dissimilarity)) +
  scale_x_continuous(limits = c(0, 1500), name = "Distance to initiator") +
  geom_col(width = 100) +
  xlab('Distance to block leader')

enter image description here

TvCasteren
  • 449
  • 3
  • 18
  • 3
    You could try `+ geom_text(aes(label = building_dissimilarity), vjust = -.1)`. For more help I would suggest to provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Feb 14 '23 at 09:25

0 Answers0