Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Label column in stacked bar chart ggplot2

I am creating a stacked bar chart using the following code:

df <- structure(list(stage = structure(c(2L, 3L, 2L, 
2L, 2L, 3L, 1L, 3L, 1L, 3L, 2L, 2L, 1L, 2L, 2L, 3L, 2L, 3L, 2L, 
2L, 3L, 2L, 3L, 2L, 2L, 2L, 3L, 2L, 2L, 2L, 3L), levels = c("1", 
"2", "3"), class = c("ordered", "factor")), group = structure(c(2L, 
1L, 1L, 1L, 2L, 1L, 1L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 3L, 2L, 
1L, 1L, 1L, 1L, 3L, 2L, 2L, 1L, 3L, 2L, 3L, 1L, 3L, 3L), levels = c("1", 
"2", "3"), class = c("ordered", "factor"))), row.names = 10:40, class = "data.frame")

bp <- ggplot(data=df , aes(fill = stage, x=forcats::fct_rev(group))) + 
  geom_bar(position = "fill", width = 0.7, color = "black", size = 0.2) + 
  coord_flip()

enter image description here

I would like to label the top column with the different levels for "stage" ie. "stage 3", "stage 2", "stage 1", someting similar to this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

Any suggestions how to accomplish this?

>Solution :

The simplest way to do this is probably with a secondary y axis

ggplot(data=df , aes(fill = stage, x=forcats::fct_rev(group))) + 
  geom_bar(position = "fill", width = 0.7, color = "black", size = 0.2) + 
  coord_flip() +
  scale_y_continuous(sec.axis = sec_axis(~.x, breaks = c(0.13, 0.55, 0.92),
                                         labels = c("Oil", "Coal", "Gas"))) +
  scale_x_discrete(expand = c(0.05, 0.05)) +
  theme_minimal(base_size = 20) +
  theme(axis.ticks = element_line())

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading