StatsAreHard
StatsAreHard

Reputation: 136

Method of ordering groups in ggplot line plot

I have created a plot with the following code:

df %>% 
  mutate(vars = factor(vars, levels = reord)) %>% 
  ggplot(aes(x = EI1, y = vars, group = groups)) + 
    geom_line(aes(color=groups)) + 
    geom_point() +
    xlab("EI1 (Expected Influence with Neighbor)") +
    ylab("Variables")

The result is:

enter image description here

While the ei1_other group is in descending order on x, the ei1_gun points are ordered by variables. I would like both groups to follow the same order, such that ei1_gun and ei1_other both start at Drugs and then descend in order of the variables, rather than descending by order of x values.

Upvotes: 1

Views: 792

Answers (1)

stefan
stefan

Reputation: 125797

The issue is that the order by which geom_line connects the points is determined by the value on the x-axis. To solve this issue simply swap x and y and make use of coord_flip.

As no sample dataset was provided I use an example dataset based on mtcars to illustrate the issue and the solution. In my example data make is your vars, value your EI1 and name your groups:

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

example_data <- mtcars %>%
  mutate(make = row.names(.)) %>%
  select(make, hp, mpg) %>% 
  mutate(make = fct_reorder(make, hp)) %>% 
  pivot_longer(-make)

Mapping make on x and value on y results in an unordered line plot as in you example. The reason is that the order by which the points get connected is determined by value:

example_data %>% 
  ggplot(aes(x = value, y = make, color = name, group = name)) + 
  geom_line() + 
  geom_point() +
  xlab("EI1 (Expected Influence with Neighbor)") +
  ylab("Variables")

In contrast, swapping x and y, i.e. mapping make on x and value on y, and making use of coord_flip gives a nice ordererd line plot as the order by which the points get connected is now determined by make (of course we also have to swap xlab and ylab):

example_data %>% 
  ggplot(aes(x = make, y = value, color = name, group = name)) + 
  geom_line() + 
  geom_point() +
  coord_flip() +
  ylab("EI1 (Expected Influence with Neighbor)") +
  xlab("Variables")

Upvotes: 1

Related Questions