Home > Enterprise >  How to sort parameters on y-axis based on a category in ggplot R
How to sort parameters on y-axis based on a category in ggplot R

Time:07-20

Lets say I have the following dataset:

dt <- data.frame(Days= sample(1:50, 10),
                 Individual= sample(letters, 10),
                 Category= sample(c("A","B","C"), 10, replace = TRUE))

and I want to create a scatter plot using ggplot by the following code:

ggplot(dt, aes(x=Days, y=Individual, colour= Category, size= 5)) 
  geom_point()

As shown in the following plot, categories are mixed because ggplot ordered y-axis based on alphabet orders:

enter image description here

I want the y-axis be ordered based on the category. So points with the same color are shown next to each other. I tried the following code:

dt %>%
  mutate(Category = fct_relevel(Category, "A", "B", "C")) %>%
  ggplot(dt, mapping= aes(x=Days, y=Individual, colour= Category, size= 5)) 
  geom_point()

Which is used from the following source:

https://r-graph-gallery.com/267-reorder-a-variable-in-ggplot2.html

I tried other possible solutions on that link. But I am not still getting the result I want. What am I doing wrong?

CodePudding user response:

You could try ordering first then using fct_inorder to "lock" the Individual levels in order:

dt <- data.frame(Days= sample(1:50, 10),
                 Individual= sample(letters, 10),
                 Category= sample(c("A","B","C"), 10, replace = TRUE))

library(ggplot2)
library(forcats)
library(dplyr)

dt %>%
  arrange(Category, Days) %>%
  mutate(Individual = fct_inorder(Individual)) %>%
  ggplot(dt, mapping= aes(x=Days, y=Individual, colour= Category, size= 5)) 
  geom_point()

  • Related