user2894356
user2894356

Reputation: 139

arrange does not order the data as expected for plotting with ggplot2

I would like to plot some data. Somehow the data is not ordered correct so that the order on the x-axis is wrong (1100, 1200, 200 instead of 200, 1100, 1200).

MWE:

require(data.table)
require(tidyverse)
dt <- data.table("1100" = c(20,30,40), "1200" = c(44,23,2), "200" = c(32,42,1))

dt %>% 
    rownames_to_column("ID") %>% 
    mutate(ID = as.numeric(ID)) %>%
    gather(vars, value, -ID) %>%
    arrange(vars) %>% # does not work as expected
    ggplot(aes(vars, value, color = ID, fill = ID)) + 
    geom_jitter() 

What do I need to change?

Upvotes: 1

Views: 442

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388862

Convert vars to factor and assign levels based on their integer value.

library(tidyverse)

dt %>% 
 rownames_to_column("ID") %>% 
 mutate(ID = as.numeric(ID)) %>%
 gather(vars, value, -ID) %>%
 mutate(vars = factor(vars, levels = sort(unique(as.integer(vars))))) %>%
 ggplot(aes(vars, value, color = ID, fill = ID)) + 
 geom_jitter() 

enter image description here

PS - gather is retired in the newer version of tidyr, use pivot_longer instead.

Upvotes: 6

Related Questions