r - 在 y 范围改变后标记堆叠条形图(用 ggplot 制作)

标签 r ggplot2

由于我的堆积条形图显示百分比,并且一个变量始终为 90% 以上,因此我更改了绘图的范围,以便更好地查看其他变量。 我现在的问题是,添加标签后,90%+ 的一个变量的标签不再显示(因为它位于查看区域之外)。

代码:

ggplot(data=USB_Carbapenem_DDD_Perc_long, aes(x=Monat, y=DDDs, fill=`API`)) +
  geom_bar(stat="identity") + 
  theme(legend.position="bottom", legend.title = element_blank(), axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_continuous(name="Relativer DDD-Verbrauch", labels = percent_format(accuracy=1)) +
  geom_text(aes(label=paste0(DDDs*100,"%")), position=position_stack(vjust=0.5), size=3.5, label.padding=1) + 
  coord_cartesian(ylim = c(0.85, 1))

现在的样子: enter image description here

我的数据(通过dput创建):

structure(list(API = c("ertapenem", "imipenem and cilstatin", 
"meropenem", "rest", "ertapenem", "imipenem and cilstatin", "meropenem", 
"rest", "ertapenem", "imipenem and cilstatin", "meropenem", "rest", 
"ertapenem", "imipenem and cilstatin", "meropenem", "rest", "ertapenem", 
"imipenem and cilstatin", "meropenem", "rest", "ertapenem", "imipenem and cilstatin", 
"meropenem", "rest", "ertapenem", "imipenem and cilstatin", "meropenem", 
"rest", "ertapenem", "imipenem and cilstatin", "meropenem", "rest", 
"ertapenem", "imipenem and cilstatin", "meropenem", "rest", "ertapenem", 
"imipenem and cilstatin", "meropenem", "rest", "ertapenem", "imipenem and cilstatin", 
"meropenem", "rest", "ertapenem", "imipenem and cilstatin", "meropenem", 
"rest"), Monat = structure(c(2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 
4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 
8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 11L, 11L, 
11L, 11L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L), .Label = c("Total", 
"Jan 2018", "Feb 2018", "Mär 2018", "Apr 2018", "Mai 2018", "Jun 2018", 
"Jul 2018", "Aug 2018", "Sep 2018", "Okt 2018", "Nov 2018", "Dez 2018"
), class = "factor"), DDDs = c(0.005, 0.006, 0.052, 0.937, 0.011, 
0.003, 0.05, 0.936, 0.01, 0.011, 0.056, 0.924, 0.006, 0.011, 
0.057, 0.925, 0.012, 0.006, 0.067, 0.915, 0.016, 0.016, 0.05, 
0.918, 0.013, 0.009, 0.063, 0.915, 0.019, 0.008, 0.07, 0.904, 
0.016, 0.011, 0.056, 0.918, 0.025, 0.008, 0.051, 0.915, 0.021, 
0.01, 0.048, 0.921, 0.02, 0.006, 0.066, 0.909)), row.names = 5:52, class = "data.frame")

根据要求,我希望它看起来如何: enter image description here

我尝试设置 ...position_stack(vjust=1), vjust=1, ... 以便首先将数字放在顶部,然后再次降低一点,但看起来确实很糟糕。 有办法解决吗?也许将标签放在查看区域的中间?

最佳答案

我们可以为每个 fill 级别传递一个 vjust 值,如下所示

position = position_stack(vjust = c(0.95, 0.5, 0.5, 0.5))

给予

enter image description here

关于r - 在 y 范围改变后标记堆叠条形图(用 ggplot 制作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54370036/

相关文章:

r - 字符串中数字之间的差异

r - 向 multicompview 对比图添加轴标签

r - 如何使用从 base::cut() 函数派生的轴减少 ggplot 的刻度数

r - 使用多个geom时如何使用directlabels添加标签?

r - 使用 scales = 'free' 在 facet_wrap 中设置 x/y 限制

r - 如何将文本粘贴到 R 中 ggplot2 图形的数字 y 轴刻度中?

r - 使用箭头连接一项内但跨组的点

c++ - 加载 Rcpp 模块

r - 如何在 R 中有效地重新编码多列?

r - 在 R 中使用 geom_label_repel 将标签放在前面,将引线放在后面