r - 在 R 中,如何使用 ggplot2 绘制具有 2 个分类值的三个不同值?
问题描述
我有一个原始数据集。
gender neg_sentiment neu_sentiment pos_sentiment
<fct> <int> <int> <int>
1 F 24216 10070 14734
2 M 372863 162281 239366
我想像下图一样绘制这个数据集。
你能帮我做这个吗?
dput 如下所示:
structure(list(gender = structure(1:2, .Label = c("F", "M"), class = "factor"),
neg_sentiment = c(24216L, 372863L), neu_sentiment = c(10070L,
162281L), pos_sentiment = c(14734L, 239366L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L))
解决方案
您可以从宽到长重塑,然后使用 (gg) 绘图facet_wrap
library(tidyverse)
df %>%
pivot_longer(-gender) %>%
ggplot(aes(name, value, fill = name)) +
geom_col() +
facet_wrap(~ gender)
或者经过更多的微调/抛光
df %>%
pivot_longer(-gender) %>%
mutate(name = factor(
name,
levels = c("pos_sentiment", "neu_sentiment", "neg_sentiment"),
labels = c("positive", "neutral", "negative"))) %>%
ggplot(aes(name, value, fill = name)) +
geom_col(show.legend = FALSE) +
facet_wrap(~ gender, strip.position = "bottom") +
labs(x = "") +
scale_fill_manual(
values = c("positive" = "darkblue", "neutral" = "blue", "negative" = "darkred")) +
theme_minimal()
样本数据
df <- structure(list(gender = structure(1:2, .Label = c("F", "M"), class = "factor"),
neg_sentiment = c(24216L, 372863L), neu_sentiment = c(10070L,
162281L), pos_sentiment = c(14734L, 239366L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L))
推荐阅读
- installation - 如何使完成时的启动复选框在 InstallShield 6.0 中正常运行?
- python-3.x - 如何使用 numpy.save 有效地更新文件数据?
- rust - 解析一个整数,忽略任何非数字后缀
- python - 尝试在使用字典理解从 csv 转换字典后打印出字典的键
- vb.net - 有没有办法根据 TrackBar 中的值范围指示 if-then 语句?(VB.NET)
- php - snapchat login kit web:无效授权,无效代码验证器
- reactjs - 如何避免单个反应原生组件中的多重渲染
- docker - 构建 docker 映像失败,无法获取匿名令牌,TLS 握手超时
- java - package-info.java 如何在 maven 项目中的 main 和 test 之间共享?
- amazon-web-services - Can API Gateway use values from DynamoDB as input to request mapping template?