-1

Can anyone help me in my struggle to combine these two graphs into one? Ideally the coloured plot should be overlaid by the step plot, so that counts of "ox_0" are shown (as histogram or steps) on the coloured graph.

1

I have PLOT 1:

ggplot(subset(stw, !is.na(will)), aes(ox_0, fill=will)) +
    geom_bar(position="fill") +
    ggtitle("Willingness to repeat surgery per Oxford Knee Score at baseline") +
    xlab("Preoperative Oxford Knee Score")+ ylab("")+
    scale_y_continuous("", labels=c("0 %", "25%", "50%", "75%", "100%"))+
    theme(
    axis.text.y = element_text(size=12, color=1),
    axis.title.x = element_text(size=15, color=1),
    axis.text.x = element_text(size=12, color=1),
    axis.title.y = element_text(size=15, color=1),
    plot.title = element_text(hjust=0.5, size=16),
    strip.text.x = element_text(size=12),
    legend.text = element_text(size=13),
    legend.title = element_text(size=15))+
    scale_fill_manual("Would you repeat surgery?", values=col.traf, aesthetics = "fill")

and PLOT 2:

ggplot(subset(stw, !is.na(will)), aes(ox_0))+
    stat_bin(geom="step", binwidth = 1)
vimuth
  • 5,064
  • 33
  • 79
  • 116
Anne MP
  • 3
  • 1
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 28 '23 at 23:23
  • In general you could add the stat_bin layer to your first plot, i.e try with `+ stat_bin(data = subset(stw, !is.na(will)), aes(ox_0), geom="step", binwidth = 1, inherit.aes = FALSE)`. However, your probably have to rescale the count for the stat_bin because of the different scales. For more help see the comment by MrFlick. – stefan Feb 28 '23 at 23:48
  • Thanks to you both for helping me. I used this other solution below, because it seemed easier for me, and that worked. – Anne MP Mar 01 '23 at 08:15

1 Answers1

0

Here's an example with a dataset from dplyr. In this case I put the fill aesthetic into only the geom_bar layer, and use y = after_stat(count)/1000 to bring the range of the 2nd layer (max value 684) into the range 0:1 that the "fill" bars will necessarily cover. Here I add a secondary axis label to show how the step line should be interpreted.

ggplot(dplyr::storms, aes(day)) +
  geom_bar(aes(fill = status), position = "fill") +
  stat_bin(geom = "step", binwidth = 1, aes(y = after_stat(count)/1000)) +
  scale_y_continuous(sec.axis = sec_axis(~ . *1000))

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53