1

I am plotting a dataframe and the x values are "first", "second" ... so on.

The ggplot function plotted them alphabetically instead of numerically.

I tried to use

scale_fill_discrete(
  breaks = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
)

The barplot is still coming out with the wrong order here is the full code

gender_1 %>% 
  ggplot(aes(x = `Call Attempt`, y = `Count`, fill = `Gender`)) +
  geom_col(position dodge) + 
  scale_fill_discrete(
    breaks = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
  )

I used

scale_fill_discrete(
  breaks = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
)

and the order came out alphabetically instead of numerically

stefan
  • 90,330
  • 6
  • 25
  • 51
armandp
  • 11
  • 2
  • It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Oct 27 '22 at 05:45
  • This said: As you want to order "the x values" try with `scale_x_discrete` instead of `scale_fill_discrete` and use the `limits` instead of the `breaks`, i.e. do `scale_x_discrete(limits = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth"))`. – stefan Oct 27 '22 at 05:50
  • Can you post sample data? Please edit the question with the output of `dput(gender_1)`. Or, if it is too big with the output of `dput(head(gender_1, 20))`. – Rui Barradas Oct 27 '22 at 06:28

1 Answers1

0

You probably want to use an (ordered) factor for your gender variable:

library(ggplot2)
# Example data

Gender<-c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
frame<-data.frame(X=1:6,Y=rnorm(6),Gender)

# ggplot orders this alphabetically (not what you want)
ggplot(frame,aes(X,Y,fill=Gender))+
  geom_bar(stat="identity")

# by using a factor and explicitly specifiying 
# its levels (and the order of the levels) you force ggplot to abandon alphabetical order

ggplot(frame,aes(X,Y,fill=factor(Gender,levels = Gender)))+
  geom_bar(stat="identity")
shghm
  • 239
  • 2
  • 8