3
votes

It was suggested that this is a duplicate from ggplot2 geom_bar ... how to keep order of data.frame

The difference is that the post in that my categorical variables are actually numbers as factors where that post uses strings. When I use that solution, my numbers still do not plot in numeric order.

I've ran a GLM model with numbers that are actually brought in as factors. They are brought in this way because the first four numbers are actually dummy variables for a class and the rest are actual numbers. I would like to plot these factors in number order though. Is there a way to do this? The problem can be produced with the code below:

library(ggplot2)

x <- c("1", "2", "3", "4", "100", "250", "350", "450")
y<- (1:8)
df <- data.frame(x, y)

ggplot(df, aes(x = x, y = y)) +
  geom_bar(stat = "identity")

I have looked at the following posts: Keeping order for ggplot bar chart in R

Variables order for ggplot

Data frame variable order for ggplot

1
what is number order ? And why not using a solution provided in the linked answers? In addition you should use geom_col() instead of geom_bar().Roman
What's wrong with suggested posts? You can also do this: scale_x_discrete(limits = x)pogibas
number order would mean (1, 2, 3, 4, 100, 250, 350, 450) . I didn't use the answers because they didn't seem to work.Jordan

1 Answers

10
votes

You can use reorder():

ggplot(df, aes(x = reorder(x, sort(as.numeric(x))), y = y)) +
  geom_bar(stat = "identity")

output