I am looking for a solution in [R] to make a chart like I show here (it is made in Excel):
I can make a histogram using below code:
ggplot(data=TestData, aes(x=
QP1)) + geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 0.1, fill = "lightblue", color="black")+ scale_x_continuous(breaks = seq(8,10,0.1)) + scale_y_continuous(labels = percent_format(), breaks = seq(0,1,0.05)) + xlab("QP1")
but I could not make a secondary axis and a line plot overlaid on the histogram. I found several example on this site asking similar question, but still had difficulty in truly understanding those solutions.
I need help for:
- Recommended code to achieve cumulative line plot, but appreciate if some guidance is added to explain the mechanism behind working.
- I want to control bin width nicely and add some statistic like mean/stdev etc on the chart, am not lazy if have to use dplyr or do some additional working.
Thanks.
Edit:
I could achieve what I wanted initially. During further enhancement, such as adding adding data labels is a challenge in this matter:
ggplot(data=TestData, aes(x=QP1, y=after_stat(count / sum(count)))) +
geom_histogram(fill = "darkorange", color="black", binwidth = 0.1) +
stat_bin(aes(y = after_stat(cumsum(count / sum(count)) * 0.5)),
geom = "line", colour = "dodgerblue",binwidth = 0.1) +
stat_bin(aes(label = after_stat(scales::percent(count / sum(count)))),
geom = "text",colour="blue", binwidth = 0.1,vjust=1) +
stat_bin(aes(label = after_stat(scales::percent(cumsum((count / sum(count)))))),
geom = "text",colour="blue", binwidth = 0.1, vjust=-4) +
scale_y_continuous(
labels = scales::percent, breaks = seq(0,5,.1),
name = "Proportion",
sec.axis = sec_axis(~ .x * 2,
name = "Cumulative Proportion",
labels = scales::percent, breaks = seq(0,1,.2)))
Data labels are added well and show correct numbers, cumulative labels need to be positioned as per sec.axis, how to do that? if we transform by add/div, label value changed not the position. Please suggest.
question from:
https://stackoverflow.com/questions/65830791/a-histogram-with-individual-proportions-on-one-y-axis-and-cumulative-proportion