r - 堆积条形图:如何使用 forcats 包排列组
问题描述
我正在制作一些漂亮的情节,我可以在需要时复制粘贴(这就是我包含这么多选项的原因)。所以我有这个情节:
library(tidyverse)
mtcars %>%
group_by(cyl) %>%
summarise(n=n()) %>%
ungroup() %>%
mutate(cars = "cars") %>%
ggplot(aes(x = as.factor(cars), y = n, fill=as.factor(cyl))) +
geom_bar(stat="identity", width = .3) +
geom_text(aes(label = paste0(round(n, digits = 0), "stk.")),
position = position_stack(vjust = 0.5)) +
labs(title = "Number of cars with cylinders in the data set",
subtitle= "If needed",
caption= "Fodnote",
x= "", y="Antal",
fill="# of cylinders") +
theme(#legend.position="none",
plot.caption = element_text(hjust = 0))
我如何重新排序堆栈,例如蓝色在底部,然后是红色堆栈和绿色堆栈在顶部。谢谢。我认为解决方案涉及forcats
...
解决方案
这是你要找的吗?要更改填充颜色,请使用scale_fill_manual()
或scale_fill_brewer()
library(tidyverse)
library(forcats)
mtcars %>%
group_by(cyl) %>%
summarise(n=n()) %>%
ungroup() %>%
mutate(cars = "cars",
cars = factor(cars),
cyl = factor(cyl)) %>%
# use fct_reorder here
mutate(cyl = fct_reorder(cyl, n)) %>%
ggplot(aes(x = cars, y = n, fill = cyl)) +
geom_col(width = .3) +
geom_text(aes(label = paste0(round(n, digits = 0), "stk.")),
position = position_stack(vjust = 0.5)) +
labs(title = "Number of cars with cylinders in the data set",
subtitle = "If needed",
caption = "Footnote",
x = "", y = "Antal",
fill = "# of cylinders") +
theme(#legend.position="none",
plot.caption = element_text(hjust = 0))
推荐阅读
- r - 使用“rvest”在 R 中进行网络抓取时,将其他变量合并到基于特定行信息的数据的最佳实践是什么?
- powershell - Powershell - 多个 Exchange 服务器的 MailboxFolderPermissions 问题
- javascript - 通过道具删除东西
- c++ - C ++如何从函数返回对象数组
- php - Laravel 模型是表的范围
- sql - SQL:按日期选择所有数据更改(从历史表中)
- java - 如何从未初始化的活动中更改对象的字段
- ios - 自定义页脚视图没有响应我的点击手势识别器标签
- java - 在 Netbeans 中增加输出和菜单的字体大小的问题
- powerbi - 需要公式在 power bi 报告中应用