I asked people how many years they have been smoking and afterwards I calculated the risk to die for groups of smoking duration. Lets assume this data:
df <- data.frame(years_smoke= c(1,2,2,3,3,3,4,5,6, 6,7, 10, 11, 12, 12, 14, 15),
risk_death= c(rep(.1, 8), rep(.3, 4), rep(.7, 5)))
Here the continuous variables years_smoke is split up into three groups (1 to 5 years, 6 to 10 years and 11 to 15 years) and each group has a death risk value (it is .1 for those smoking 1 to 5 years, .3 for those smoking 6 to 10 years and .7 for the once smoking 11 to 15 years).
I want to plot the countinuous variable years_smoke as a histogram and to colour the columns by the risk of the groups like a heatmap, where low risk to die is green and high risk to die is red, for example. So far, in the comments (and in two deleted answers) something like this was suggested:
library(ggplot2)
ggplot(df, aes(years_smoke, fill= factor(risk_death))) + geom_histogram()
But this does not work as expected. If we change the data to
data.frame(years_smoke= c(1,2,2,3,3,3,4,5,6, 6,7, 10, 11, 12, 12, 14, 15),
risk_death= c(rep(.1, 8), rep(.3, 4), rep(999, 5)))
we will get the very same plot as before. But in case of a heatmap this should result in very different colours where all columns with risk .1 and .3 have pretty much the same green colours and the risk group 999 has a very red colour. This question was marked as a duplicate. But the link provided also does not give colours like in a heatmap because of the usage of fill by a factor, where the colours do not depent on the actual value of a continuous variable.
(data is made up)