Search code examples
rggplot2dot-plot

How to reorder a dot plot in R


I have this dataset on the percentage of individuals who own a car in five different cities between 1992 and 1999:

city <- c("A", "A", "B", "B", "F", "F", "T", "T", 
             "C", "C") 
year <- c("1992", "1999", "1992", "1999", "1992", "1999", "1992", "1999", "1992", "1999")
# variable 2
car_owner <- c("15.9", "75.6", "35.8", "95.2", "15.9", "74", "6", "64", "41", "97.9")

df <- data.frame(city, year, car_owner)
df$car_owner <- as.numeric (df$car_owner)

Now I use this code and create a dot plot:


df %>%
  group_by(city) %>%
  mutate(Difference = car_owner - lead(car_owner),
         Position = car_owner - (0.5 * Difference)) %>%
  ggplot(aes(x = car_owner, y = city))+
  geom_vline(xintercept = c(),
             lty = 2, alpha = 0.5) +
  geom_line(aes(group = city)) +
  geom_point(aes(color = year), size=3) +
  geom_text(aes(label = abs(Difference),
                y = city,
                x = Position),
            nudge_y = 0.2) +
  theme_classic(base_size = 12) +
  labs(x = "Car owner)")+
  theme(legend.position = "top") +
  scale_color_brewer(palette = "Accent", direction = ) +
  theme(axis.ticks.y = element_line(colour = c("transparent",
                                               rep("black", 12))))

The plot shows all the information. However, what I would like to do is to order the graph based on the magnitude of the difference between years. So city A should be the first one (59.9 percentage point increase) and then B, F, T, and finally C.

Dot plot


Solution

  • Using reorder you could reorder city by the absolute difference of car_owner like so:

    library(dplyr)
    library(ggplot2)
    
    df_label <- df %>%
      group_by(city) %>%
      summarise(
        Difference = diff(car_owner),
        Position = mean(car_owner)
      )
    
    df %>%
      mutate(city = reorder(city, car_owner, function(x) abs(diff(x)))) %>%
      ggplot(aes(x = car_owner, y = city)) +
      geom_line(aes(group = city)) +
      geom_point(aes(color = year), size = 3) +
      geom_text(
        data = df_label,
        aes(
          label = abs(Difference),
          y = city,
          x = Position
        ),
        nudge_y = 0.2
      ) +
      theme_classic(base_size = 12) +
      labs(x = "Car owner)") +
      theme(legend.position = "top") +
      scale_color_brewer(palette = "Accent", direction = ) +
      theme(axis.ticks.y = element_line(colour = c(
        "transparent",
        rep("black", 12)
      )))
    

    enter image description here