r - R geom_bar:按组可视化单个大小和总大小
问题描述
所以我想制作一个条形图来按组可视化个人大小和总大小。
为了按组分隔值,我使用了Position = 'dodge'
. 为了绘制总大小,我使用了stat = 'identity'
. 为了可视化个人大小,我使用了aes(color='black')
.
这三个似乎不能一起工作。
# make fake data
t1 = tibble(type = c('a', 'b', 'c', 'a', 'a'), Quantity = c(100, 200, 150, 50, 75), fill=c('1','1','1','2','2'))
# no dodge, correctly stacked
p1 = ggplot(t1) +
geom_bar(aes(type, Quantity, fill=fill, color='black'),
stat='identity', alpha=0.5) +
scale_color_manual(values='black', guide=FALSE)
# with dodge, overlap in same group
p2 = ggplot(t1) +
geom_bar(aes(type, Quantity, fill=fill, color='black'),
stat='identity', alpha=0.5, position='dodge') +
scale_color_manual(values='black', guide=FALSE)
p1 / p2
这个例子是根据2017年发的这篇帖子修改的。在帖子中,解决方案是合并同一组的数据点。但在我的情况下,如果合并数据,将没有信息来绘制单个大小。既然是 2021 年,还有其他解决方案吗?
解决方案
您应该先计算总数并尝试绘制。例如,此代码生成以下图。我不确定是否fill
需要列
t1 = tibble(type = c('a', 'b', 'c', 'a', 'a'), Quantity = c(100, 200, 150, 50, 75))
p2 = t1 %>%
group_by(type) %>%
mutate(total = sum(Quantity)) %>%
pivot_longer(-type) %>%
ggplot() +
geom_bar(aes(type, value, fill=name, color='black'),
stat='identity', alpha=0.5, position='dodge') +
scale_color_manual(values='black', guide=FALSE)
推荐阅读
- reactjs - React-Materialize Modal :任何键都会意外关闭模态
- c++ - 在 C++ 中为公共类变量声明两种或多种类型
- unit-testing - 在 Azure Devops yaml 构建管道中运行时如何指定 SSDT 单元测试的连接详细信息
- azure-storage - Azure Java SDK:具有多个卷的容器
- repository - DDD 中的存储库应该返回什么
- react-native - React Native - 重新运行渲染方法
- compilation - 如何编译静态球拍二进制文件
- javascript - 在制表器网格中呈现 7k 条记录的加载时间非常慢
- c++ - C++ 联合 , 交集 , 差异
- ms-access - MS-Access 报告文本框控件源参数