0
votes

My sample data frame goes as follows:

a <- structure(list(Middlepoint = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 
12, 13, 14, 15, 16, 17, 18, 19, 1, 1, 5, 5, 4, 4, 3, 7, 18, 8, 
8, 8, 8, 8, 8.5, 8.5)), .Names = "Middlepoint", class = "data.frame", row.names = c(NA, 
-34L))

I would like to create a histogram of binwidth = 1 and of the characteristics as follows:

library(ggplot2)
library(scales)
ggplot(a, aes(x = Middlepoint)) + 
  geom_histogram(aes(y = ..density.., fill=..density..), binwidth = 1) + 
  scale_x_continuous(breaks=0:19) + 
  scale_fill_continuous(low = "red", high = "green")

Now, what I cannot figure out is how to color just the bin of highest density (here, bin 8-9) with green color and all other bins with red (no gradient, just straight colors).

As you can see from the code above, the closest I could get to the desired outcome is to use scale_fill_continuous() component which is close but not exactly how I would like to see it. I tried threads like ggplot change fill colour without losing colour gradient and R - ggplot2 histogram conditional fill color. Any ideas how to generally custom fill histogram's bins?

1
There is no percent object in your example.user3710546
Add library(scales)Martin Schmelzer
Thnx for answers & hints! The general idea behing is because the only acceptable occuring values should be withing the green bin (8€-9€). The others, red bins are not acceptable, hence, visual issue that results in my problem. @HenrikPatrik_P
@Henrik Bin with the highest density is the reasoning you are looking for. I did not consider ties with x values per se, I considered the color ties with the bin of highest density. Thanx for advice I will be more knowledgeable in the future Qs. Cheers!Patrik_P

1 Answers

2
votes

You need to set the fill argument to a factor which takes 2 levels: one for all the density values lower then the max and one for the maximum density:

ggplot(a, aes(x = Middlepoint)) + 
  geom_histogram(aes(y    = ..density.., 
                     fill = cut(..density.., c(0, sort(..density.., TRUE)[1:2]))), 
                 binwidth = 1) + 
  scale_fill_manual("", values = c("red", "green")) +
  theme_minimal()

Histogram