r - 如何在 R 中绘制堆积条形图?
问题描述
我有一个这样的示例数据:它看起来很简单,但我无法找到出路,我是 R 新手。请帮忙!
clust4 catch
1 131711493
2 41683530
3 143101724
4 35849946
如何获得堆积条形图,通过捕获列的值显示每个集群的百分比?并获得如下图例名称:
group(legend name)
Cluster1
Cluster2
Cluster3
Cluster4
我已经尝试了很多次,但它只显示了 4 个不同的堆叠条形图,也无法将图例名称从 1、2、3、4 更改为集群 1,...)
很抱歉没有插入任何照片,因为我没有足够的声誉来做到这一点。
解决方案
解决方案1:ggplot2
library(tidyverse)
df %>% mutate(catch = catch / sum(catch),
clust4 = paste0("Cluster-", clust4)) %>%
ggplot(aes(x = "", y = catch, fill = clust4)) +
geom_bar(stat = "identity", color = "black") +
coord_flip()
解决方案2:图形
prop <- df$catch / sum(df$catch)
color <- RColorBrewer::brewer.pal(4, "Set2")
barplot(as.matrix(prop), horiz = T, col = color,
xlim = c(0, 1.2), ylim = c(-0.5, 2),
legend.text = paste0("Cluster-", 1:4),
args.legend = list(x = "right", bty = "n"))
颜色比例
clust4 catch
1 Cluster-1 0.3738122
2 Cluster-2 0.1183026
3 Cluster-3 0.4061390
4 Cluster-4 0.1017462
数据
df <- read.table(text = "clust4 catch
1 131711493
2 41683530
3 143101724
4 35849946", header = T)
推荐阅读
- laravel - 默认插槽内的组件
- typo3 - 我们如何在 TYPO3 的用户设置中的新选项卡中添加新字段
- python - 用四元数找到向量的端点
- r - 如何从数据库中抓取循环?
- ruby-on-rails - ActionController::RoutingError: 没有路由匹配 [POST] "/seekers"
- java - Spring Security - 检索当前尝试登录的用户的用户名
- angular - 如何将Child附加到角度的按钮
- python - 基于“!”的食品评论情感分析 并向 wordcloud 添加标点符号?
- c++ - 根据类型参数自动化类模板的大小参数
- python - 在 Pandas DataFrame 中动态选择多个列