ggplot:堆叠的Barplot-geom_text标签凌乱

我已根据需要对数据进行了分组,并正确地累加了数量。

现在,我想创建一个堆叠的条形图,在其中要显示每个单位的标签。

汇总数据如下:

ggplot:堆叠的Barplot-geom_text标签凌乱

要在R中阅读它:

df <- structure(list(date = structure(c(17785,17785,17785),class = "Date"),hour = structure(c(5L,5L,6L,7L,8L,9L,10L,11L,12L,13L,14L,15L,16L,16L),.Label = c("00","02","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22"),class = "factor"),lGroup = structure(c(3L,3L,4L,2L,3L),.Label = c("AHX","A1","A3","B1","C1","C3","E1","E3","E5","Andere"),unit = structure(c(2L,9L),.Label = c("Andere","Einzelartikel","Bund","BundGroesser6m","EuroPal","Pack","Verschlag","Rinnentransportkasten","Sack"),values = c(1,1,7,2,6,3,15,9,14,11,4,5,16,17,8,32,10,33,13,24,3)),row.names = c(NA,-125L),class = c("grouped_df","tbl_df","tbl","data.frame"
),groups = structure(list(date = structure(c(17785,16L
    ),"22"
    ),.rows = list(1:4,7:8,9:12,14:15,16:17,18:20,21:23,24:27,28:30,31L,32:36,37:41,42L,43:45,46:49,50L,51:52,53:58,59L,60L,61L,62:64,65:68,69L,70L,71:73,74:75,76:79,80L,81:85,86:87,88L,89L,90L,91:95,96:100,101:102,103L,104:107,108:109,110:115,116:117,118:121,122:125)),-47L),class = c("tbl_df","data.frame"),.drop = TRUE))

对于我堆积的barplot,我使用(除其他外)此代码:

ggplot(df,aes(x = hour,y = values,fill = unit,label = values)) +
  geom_bar(stat = "identity") +
  geom_text(stat = "identity",check_overlap = TRUE,hjust = -.2)

这将导致以下结果:

ggplot:堆叠的Barplot-geom_text标签凌乱

或者,我已经尝试了以下方法:

ggplot(df,label = values)) +
  geom_col(aes(fill = unit)) +
  geom_text(aes(label = values),position = position_stack(0.5))

这给我更糟糕的结果...

ggplot:堆叠的Barplot-geom_text标签凌乱

结果应如下所示(在这里,我的抛光图通过powerpoint手动填充了较大单位的值...)

ggplot:堆叠的Barplot-geom_text标签凌乱

关于如何解决此问题的任何建议?

w910488011 回答:ggplot:堆叠的Barplot-geom_text标签凌乱

您需要先处理一下数据:

library(tidyverse) 
library(RColorBrewer) # optional to have the palette red-blue

df %>%
    # group them
    group_by(hour,unit) %>%
    # summarise
    summarise(values = sum(values)) %>%
  ggplot( aes(x = hour,y = values,fill = unit,label = values)) +
  geom_bar(stat = "identity")  +
  geom_text(size = 3,position = position_stack(vjust = 0.5))+
  # here the option for the blue-red palette and light background
  scale_fill_manual(values = colorRampPalette(brewer.pal(11,"RdBu"))(8)) + theme_light() +
  # this is going to put the legend at the bottom
  theme(legend.position="bottom",legend.box = "horizontal") +
  # this is going to change the title legend,hoping not have made any mistake!
  guides(fill=guide_legend(title="Lagereinheiten"))

enter image description here

本文链接:https://www.f2er.com/3104577.html

大家都在问