如何将geom_segment()中的数据可视化按降序排列?

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

我试图在 R 中使用 ggplot/geom_segment 以降序绘制推文的 sources/devices。 这是我的代码 运行:

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)


这是它返回的图,它没有像我想要的那样呈递减模式。

所以,我想知道如何按降序绘制 geom_segment?

您使用了正确的方法,但是用错了位置。尝试在 ggplot 调用之前对数据进行因子重新排列。在您的情况下,您进行了重新排序,但随后使用了原始“源”数据,而不是 geom_segment 中重新排序的数据。在 ggplot 调用修复之前进行重新排序。 以下是使用 mtcars 数据集的示例:

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)

新情节是这样的:

改进代码:

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)