如何使 ggplot2 在此图中排除零值?

use*_*933 5 r ggplot2

R我在 中运行以下代码RStudio,输出也如下所示:

df2  %>%
  ggplot(aes(
    x = JANUARY,
    y = value,
    fill = JANUARY,
    group = year
  )) +
  geom_col(
    position = position_dodge(.65),
    width = .5
  ) +
  geom_text(aes(
    y = value + max(value) * .03,
    label = round(value * 100) %>% str_c('%')
  ),
  position = position_dodge(.65)
  ) +
  geom_text(aes(
    y = y_pos,
    label = str_remove(year, 'X')
  ),
  color = 'white',
  angle = 90,
  fontface = 'bold',
  position = position_dodge(0.65)
  ) +
  scale_y_continuous(
    breaks = seq(0, .9, .1),
    labels = function(x) round(x * 100) %>% str_c('%')
  ) +
  scale_fill_manual(values = c(
    rgb(47, 85, 151, maxColorValue = 255),
    rgb(84, 130, 53, maxColorValue = 255),
    rgb(244, 177, 131, maxColorValue = 255),
    rgb(112, 48, 160, maxColorValue = 255),
    rgb(90, 48, 100, maxColorValue = 255)
  )) +
  theme(
    plot.title = element_text(hjust = .5),
    panel.background = element_blank(),
    panel.grid.major.y = element_line(color = rgb(.9, .9, .9)),
    axis.ticks = element_blank(),
    legend.position = 'none'
  ) +
  xlab('') +
  ylab('') +
  ggtitle('Month of JANUARY (as at 01 January)')
Run Code Online (Sandbox Code Playgroud)

输出是:

柱形图

正如您所看到的,“D-Final”下的值“0%”导致条形内的标签消失在x-axis.

我想删除“0%”并将标签放回到条形内的位置。我该如何修改我的代码来实现这一目标?

df2添加数据( ):

JANUARY year  value y_pos
   <fct>   <chr> <dbl> <dbl>
 1 D-150   X2016  0.26 0.12 
 2 D-90    X2016  0.49 0.21 
 3 D-60    X2016  0.63 0.265
 4 D-30    X2016  0.73 0.325
 5 D-Final X2016  0.81 0    
 6 D-150   X2017  0.28 0.12 
 7 D-90    X2017  0.5  0.21 
 8 D-60    X2017  0.64 0.265
 9 D-30    X2017  0.77 0.325
10 D-Final X2017  0.82 0    
11 D-150   X2018  0.33 0.12 
12 D-90    X2018  0.51 0.21 
13 D-60    X2018  0.62 0.265
14 D-30    X2018  0.77 0.325
15 D-Final X2018  0.78 0    
16 D-150   X2019  0.24 0.12 
17 D-90    X2019  0.42 0.21 
18 D-60    X2019  0.53 0.265
19 D-30    X2019  0.65 0.325
20 D-Final X2019  0    0    
Run Code Online (Sandbox Code Playgroud)

Jul*_*ora 3

至少在这一点上,这并不是真正的 0%。标签的位置是预定义的并由 给出y_pos,因此您可以简单地自行更改,例如,

df2$y_pos[df2$JANUARY == "D-Final"] <- 0.4
Run Code Online (Sandbox Code Playgroud)

至于删除 0%,第一行可以替换为

df2 %>% filter(value > 0.01) %>% 
Run Code Online (Sandbox Code Playgroud)

这给出了

在此输入图像描述

显然y_pos是定义为

df2 %>% group_by(JANUARY) %>% mutate(y_pos = min(value) / 2)
Run Code Online (Sandbox Code Playgroud)

因此,为了避免此问题,在这种情况下(因为按组的所有其他值都相似),您可以改为使用

df2 %>% group_by(JANUARY) %>% mutate(y_pos = max(value) / 2)
Run Code Online (Sandbox Code Playgroud)