微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从使用 ggplot2 创建的多面条形图中删除重复的类别标签

如何解决从使用 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.2")
char_b <- c("b.1","b.2","b.1","b.1")
char_c <- c("c.1","c.1","c.2","c.3","c.4","c.5","c.5")
char_d <- c("d.1","d.2","d.1","d.2")
approach <- c("method a","method a","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,.05,"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,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")

enter image description here

在基地R你可以尝试

aggregate(result ~ variable + approach + group + value,my_data,sum)

或者干脆

aggregate(result ~ .,sum)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。