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

Customising X-axis on Stacked Bar Graph GGplot2

I would appreciate some help with changing the axis titles given the format of my current ggplot.

I’ve tried the usual arguments such as scale_x_discrete() and adding the associated labels, yet with no success.

However, overall, my goal is to keep the current format of the stacked bar, yet change 1,2,3 on the x-axis to "Cluster A" "Cluster B" "Cluster C."

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

Would really appreciate if someone could show me how to encode this while keeping the current format.

install.packages("ggplot2")
install.packages("viridis")
install.packages("hrbrthemes")

library(ggplot2)
library(viridis)
library(hrbrthemes)


x1 = rep(1:3, times = 5)
x2 = rep(0:4, times = 3)
x2 <- as.factor(x2)

df <- data.frame(x1,x2)
str(df)

ggplot(df, aes(x= x1, fill = x2), color = "x2") +
  scale_x_reverse() +
  geom_bar(position = position_fill(reverse = TRUE), stat="count") +
  theme_ipsum(axis = TRUE, grid = FALSE, axis_col = "black", axis_title_size = 10) +
  theme(plot.title = element_text(hjust = 0.5, size = 11, face = "bold"),
        axis.text = element_text(size = 11)) +
  scale_fill_viridis_d(option = "B")+
  coord_flip() 

enter image description here

>Solution :

As you have a continuous scale you have to set the labels and the breaks using scale_x_continuous or scale_x_reverse:

library(ggplot2)
library(viridis)
library(hrbrthemes)

x1 <- rep(1:3, times = 5)
x2 <- rep(0:4, times = 3)
x2 <- as.factor(x2)

df <- data.frame(x1, x2)

ggplot(df, aes(x = x1, fill = x2), color = "x2") +
  geom_bar(position = position_fill(reverse = TRUE), stat = "count") +
  theme_ipsum(axis = TRUE, grid = FALSE, axis_col = "black", axis_title_size = 10) +
  theme(
    plot.title = element_text(hjust = 0.5, size = 11, face = "bold"),
    axis.text = element_text(size = 11)
  ) +
  scale_fill_viridis_d(option = "B") +
  scale_x_reverse(breaks = 1:3, labels = paste("Cluster", LETTERS[1:3])) +
  coord_flip()

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