r - 如何在条形图(ggplot)中的条形组之间添加空间
问题描述
在 R ggplot 中,我需要制作一个条形图,其中条形图根据称为“模式”的因素组合在一起。每组钢筋之间应有间距。
我在 SO 中看到以前出现过这个问题的不同版本,但提供的答案似乎不适用于我的情况。
这是我的data.frame:
> df_mainContributors
Top_contributor Eigvec_value Mode
1 Indonesia Cassava dried 0.3489285 2
2 China, mainland Sweet potatoes -0.3280290 2
3 China, mainland Maize -0.2848236 2
4 Indonesia Potatoes -0.2749160 2
5 Thailand Cottonseed -0.3844600 3
6 Thailand Soybeans 0.3531400 3
7 Indonesia Maize 0.3308546 3
8 China, mainland Millet -0.2620598 3
9 China, mainland Potatoes -0.3883072 4
10 Thailand Rice 0.3108829 4
11 China, mainland Oil, soybean 0.2783780 4
12 Thailand Sweet potatoes 0.2754683 4
df_plot <- df_mainContributors
df_plot$Mode <- as.factor(df_plot$Mode)
df_plot$Top_contributor <- factor(df_plot$Top_contributor, levels = unique(df_plot$Top_contributor))
dodge <- position_dodge(width = 0.9)
ggplot(df_plot, aes(x = Top_contributor, y = Eigvec_value, fill = Mode)) +
geom_bar(color = "black", stat = "identity", position = dodge, width = 0.9) +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
这是组间无空格的图形:
解决方案
试试这个(我在你的 ggplot 中添加了 scale_x_discrete 的东西,不想弄乱数据框本身的内容)
ggplot(df_plot, aes(x = Top_contributor, y = Eigvec_value, fill = Mode)) +
geom_bar(color = "black", stat = "identity", position = dodge, width = 0.9) +
scale_x_discrete(limits = c(levels(df_plot$Top_contributor)[1:4],
"ABC",
levels(df_plot$Top_contributor)[5:8],
"DEF",
levels(df_plot$Top_contributor)[9:12]),
labels = c("ABC" = "",
"DEF" = "")) +
theme(axis.text.x = element_text(angle = 60, hjust = 1))
推荐阅读
- javascript - 为什么document.cookie是一个空字符串请
- powershell - 将 jpg/pdf 文件分类到已按名称存在但仅使用前 6 位数字的文件夹中
- flutter - 当我没有用 Center Widget 包裹它时,为什么我的文本在中心?
- c# - 将 DbContext 和 DbSets 中的接口用于类似数据库
- snowflake-cloud-data-platform - 将上次更改时间戳添加到雪花表中
- angular - Angular Slickgrid 使用列标题重新加载数据
- bash - bash中目录的完整性
- asp.net-core - 如何允许其他人使用 LocalDb 运行 Web App
- javascript - 在javascript中保持后端功能打开
- scripting - 用于终止 Websphere 应用程序服务器上所有 JVM 的 Jython 脚本