首页 > 解决方案 > 如何避免 ggplot 在 R 中的因子内分组

问题描述

我有以下数据:

library(tibble)
library(dplyr)
library(ggplot2)

df <-tibble::tribble(
       ~tweet_id, ~user_id, ~favourite_count,
              1L,      "a",             100L,
              2L,      "b",             111L,
              3L,      "c",             126L,
              4L,      "a",              75L,
              5L,      "d",              73L,
              6L,      "e",              64L,
              7L,      "f",              22L,
              8L,      "f",              11L,
              9L,      "g",               9L,
             10L,      "h",               9L
       ) %>% 
  mutate(tweet_id = factor(tweet_id))

所需的输出是一个包含 10 个条形图的图表,其中一个条形图代表favourite_count每个唯一的tweet_id,并且user_id作为图表上每个条形的标签。我的问题是如何阻止 ggplot 在user_id.

即图表应该包含 10 个条,每个唯一 1 个tweet_id,但是像这样的东西会在内部折叠,user_id所以图上只有 8 个条:

df %>% 
  ggplot(aes(x = favourite_count, y = reorder(user_id, favourite_count))) + 
  geom_col() 

我认为一种解决方案可能是使用 绘制绘图tweet_id,然后用来自 的值替换 y 轴标签user_id,但这会导致来自 的值排序错误user_id

df %>% 
  ggplot(aes(x = favourite_count, y = reorder(tweet_id, favourite_count))) + 
  geom_col() + 
  scale_y_discrete(labels = df$user_id)

欢迎任何建议,谢谢!

标签: rggplot2

解决方案


所需的输出是一个包含 10 个条形图的图表,其中一个条形图代表每个唯一的 tweet_id 的 favourite_count,并且 user_id 作为图表上每个条形的标签。

是你想要的吗?

library(tibble)
library(dplyr)
library(ggplot2)

df <-tibble::tribble(
  ~tweet_id, ~user_id, ~favourite_count,
  1L,      "a",             100L,
  2L,      "b",             111L,
  3L,      "c",             126L,
  4L,      "a",              75L,
  5L,      "d",              73L,
  6L,      "e",              64L,
  7L,      "f",              22L,
  8L,      "f",              11L,
  9L,      "g",               9L,
  10L,      "h",               9L
) %>% 
  mutate(tweet_id = factor(tweet_id))


ggplot(data = df, aes(x = tweet_id, y = favourite_count, label = user_id)) +
  geom_bar(stat = "identity") + # "identity" to use the value of "favourite_count"
  geom_text() # add labels on each bar

输出 :

在此处输入图像描述

[编辑]

您的评论是另一个想法,当然您可以自定义颜色,但这不是重点。

ggplot(data = df, aes(x = reorder(user_id, -df$favourite_count), y = favourite_count, fill = tweet_id)) +
  geom_bar(stat = "identity", position = "dodge") + # "identity" to use the value of "favourite_count"
  scale_x_discrete(name = "user_id")

输出 :

更多想法


推荐阅读