r - 如何避免 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)
欢迎任何建议,谢谢!
解决方案
所需的输出是一个包含 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")
输出 :
推荐阅读
- c# - 使用视图模型并将查询传递给同一视图
- javascript - 单击链接后更改其 CSS 属性的元素的正确名称是什么
- javascript - parroller.js 在第一次加载页面时无法正常工作
- sockets - 将数据发布到 HiveMQ 服务器时出现 "cleaning in abortwrite for socket 3" 错误
- python - 使用 Python 的拼写游戏
- ruby-on-rails - 如何过滤预加载有很多关联
- bluetooth - 发送/接收数据 Nodemcu(V3) + 蓝牙模块 HC-05
- android - 如何整合 Google Pay?
- python - 高斯过程的对数边际似然的sklearn计算是正的?
- windows - 需要确定以太网适配器的网络访问类型