5

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

Jordan
  • 1,415
  • 3
  • 18
  • 44
  • 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 Feb 26 '18 at 14:51
  • What's wrong with suggested posts? You can also do this: `scale_x_discrete(limits = x)` – pogibas Feb 26 '18 at 14:53
  • `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 Feb 26 '18 at 14:53
  • Possible duplicate of [ggplot2 geom\_bar ... how to keep order of data.frame](https://stackoverflow.com/questions/38131596/ggplot2-geom-bar-how-to-keep-order-of-data-frame) – Roman Feb 26 '18 at 14:58

1 Answers1

12

You can use reorder():

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

output

clemens
  • 6,653
  • 2
  • 19
  • 31
  • Thank you. So I have the actual data in a data frame in tidy format with all variables in one column and their corresponding value in another. Some of those variables are strings. Stating that, using the technique you describe didn't yield the right order. Could that have something to do with the fact that the data is in tidy format with numbers and categorical variables? – Jordan Feb 26 '18 at 15:05
  • try: `reorder(as.numeric(as.character(x)))` – clemens Feb 26 '18 at 15:13
  • The message was `Error in tapply(X = X, INDEX = x, FUN = FUN,...)` I also got another warning message that stated `In sort(as.numeric(as.character(value))): NAs introduced by coercion` – Jordan Feb 26 '18 at 15:29
  • I had to take the `reorder` command out of the function. It ran just like I intended. Thank you. – Jordan Feb 26 '18 at 18:39