Search code examples
rggplot2plotsegment

How to arrange data visualization in geom_segment() in a decreasing order?


I was trying to plot tweets' sources/devices in a decreasing order using ggplot/geom_segment in R. Here is the code I ran:

ggplot(data = device, mapping = aes(x = fct_reorder(as.factor(source), n), y = n)) +
geom_segment(aes(x = source, xend = source, y = 0, yend = n)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, family = "sans")) +
labs(title = "Tweets by device/source", x = "device/source", y = "frequency") +
geom_point(size = 4, color = "red", fill = alpha("yellow", 0.3), alpha = 0.7, shape = 21, stroke = 2)


Here is the plot it returned, which is not in decreasing pattern as I wanted to be.

the plot is here

So, I was wondering how could I plot the geom_segment in decreasing order?


Solution

  • You used the correct approach, but at the wrong spot. Try to do the factor rearrangement on your data before the ggplot call. In your case you did the reordering, but then used the original "source" data and not the reordered one in geom_segment. Doing the reordering before the ggplot call fixes that. Here is an example using the mtcars dataset:

    mtcars %>%
      rownames_to_column("model") %>%
      as_tibble() %>%
      mutate(model = fct_reorder(model, -mpg)) %>%
      ggplot() +
      geom_segment(aes(x = model, xend = model, y = 0, yend = mpg)) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1, family = "sans")) +
      labs(title = "Tweets by device/source", x = "device/source", y = "frequency") +
      geom_point(aes(x = model, y = mpg), size = 4, color = "red", fill = alpha("yellow", 0.3), alpha = 0.7, shape = 21, stroke = 2)
    

    enter image description here