0

I'm trying to make a Lollipop graph in ggplot2 by forcing the order of the x-axis using scale_x_discrete(). Here is my code:

df <- read.csv("df.csv")
# This is how my df is organized
# > head(df)
#  class categ percentage
#1    CW     A       0.37
#2    CW     B       0.63
#3    MR     A       1.00
#4    MR     B       0.00
#5    OS     A       0.33
#6    OS     B       0.67
#
# Lollipop chart
df1 <- df %>%
       arrange(categ, desc(percentage)) %>%
       mutate(class2 = df$class[order(df$categ, -df$percentage)])
#
g <- ggplot(df1, aes(x = class2, y = percentage, label = categ)) + 
     geom_point(stat='identity', aes(col = categ), size=3) + 
     geom_segment(aes(x = class2, 
                   y = min(percentage),
                   xend = class2,
                   yend = max(percentage))) + 
     scale_color_manual(labels = c("Category A", "Category B"), 
                        values = c("A"="#00ba38", "B"="#f8766d")) + 
     labs(title="Lollipop Chart") + 
     theme(axis.text.x = element_text(angle=65, vjust=0.55)) +
     scale_y_continuous(labels = percent) + scale_x_discrete(limits = df1$class2) +
     labs(x="", y="") 
plot(g)

However, my plot ends up having a very long x-axis that I'm not able to fix:

my plot

I think the problem is on scale_x_discrete(limits = df1$class2), but I have no idea how to fix this. If I don't force the x-axis order, the graph then looks normal but it's not ordered as I need -- the graph must be ordered from highest to lowest percentage of category "A".

neilfws
  • 32,751
  • 5
  • 50
  • 63
frib
  • 13
  • 3
  • 1
    Please share your data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so we can copy/paste to run and test the code. Maybe `scale_x_discrete(limits = unique(df1$class2))`? – MrFlick Dec 15 '20 at 04:11
  • Yes! scale_x_discrete(limits = unique(df1$class2)) works great, thank you so much!! – frib Dec 15 '20 at 04:42

0 Answers0