r - 从使用 ggplot2 创建的多面条形图中删除重复的类别标签
问题描述
我正在尝试使用 ggplot2 在 R 中创建一个多面条形图。我设法创建了情节,但我无法弄清楚如何正确注释它。请考虑以下 R 代码:
library(ggplot2)
library(reshape)
result <- c(0.05, 0.06, 0.08, 0.04, 0.05, 0.09, 1.05, 0.75, 1.4, 1.45)
group <- c("group.1", "group.1", "group.2", "group.1", "group.2", "group.1", "group.1", "group.2", "group.2", "group.2")
char_b <- c("b.1", "b.2", "b.2", "b.2", "b.1", "b.2", "b.2", "b.1", "b.1", "b.1")
char_c <- c("c.1", "c.1", "c.2", "c.2", "c.3", "c.3", "c.4", "c.4", "c.5", "c.5")
char_d <- c("d.1", "d.2", "d.1", "d.1", "d.2", "d.2", "d.1", "d.2", "d.2", "d.2")
approach <- c("method a", "method a", "method a", "method a", "method a", "method b", "method b" , "method b", "method b", "method b")
my_data <- data.frame(result, group, char_b, char_c, char_d, approach, stringsAsFactors=TRUE)
my_data <- melt(my_data, id=c("result","group","approach"))
df_plot <- ggplot(my_data, aes(x=variable, y=result, fill=value)) +
geom_bar(stat="identity") +
geom_text(aes(label = value),
position = position_stack(vjust = 0.5)) +
facet_wrap(approach ~ group, scales="free_x") +
theme(
legend.position="none",
axis.title.y = element_blank(),
strip.text.x = element_text(margin = margin(.05, 0, .05, 0, "cm"))
) +
coord_flip()
df_plot
上面的代码产生以下结果:
如您所见,此图的问题在于标签重复(例如,d.1、c.1 和 b.2 的标签在方法 a、group.1 的图中出现了两次)。我想知道是否可以为每个级别的类别只显示一个标签。我认为出现这个问题是因为我必须重塑数据框来创建构面;尽管如此,我一直无法解决它。
非常感谢您的帮助。
最好的祝愿,
解决方案
你可以去一个tidyverse
。但诀窍是事先总结数据。
library(tidyverse)
data.frame(result, group, char_b, char_c, char_d, approach, stringsAsFactors=TRUE) %>%
pivot_longer(cols = -c("result","group","approach")) %>%
group_by(approach, group, name, value) %>%
summarise(result = sum(result)) %>%
ggplot(aes(name, result, fill = value)) +
geom_col(show.legend = F) +
geom_text(aes(label = value),
position = position_stack(vjust = 0.5)) +
coord_flip() +
facet_wrap(approach ~ group, scales="free_x")
在基地R
你可以试试
aggregate(result ~ variable + approach + group + value, my_data, sum)
或者干脆
aggregate(result ~ ., my_data, sum)
推荐阅读
- electron - electron-builder 便携式应用程序在构建后无法运行
- c# - 在 .net 核心中使用 System.Text 反序列化流
- svg - CSS 动画通过类工作,但不能通过父元素的数据名称工作
- sas - 基于具有重复值的两个分组字段创建序列
- json - PowerBI:如何使用电源查询定位 JSON 树中的值?
- svg - 如何在 Blazor wasm .NET 5 中使用内联 svg
- keras - 在keras中将连接输入传递给LSTM的问题
- amazon-web-services - 无服务器框架、yaml 和 AWS lambda/DynamoDB 概念
- aws-sdk-go - S3 PutObject 附加查询参数
- r - 如何在 R 中查看日期 plot3D 而不是 5 位整数