1

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?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
tores
  • 35
  • 5

2 Answers2

1

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

Mojoesque
  • 1,166
  • 8
  • 15
  • This solved the problem but without the "rownames_to_column" function. – tores Aug 26 '21 at 15:49
  • Great! The `rownames_to_column` is only necessary to get the mtcars data into the correct format since I don't have access to your data. – Mojoesque Aug 26 '21 at 15:51
0

The new plot looks like this:

new plot

The improved code:

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