更改y范围后,标记堆叠的条形图(由ggplot制作)

时间:2019-01-25 17:22:13

标签: 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, ...,以便首先将数字放在顶部,然后再降低一点,但是看起来确实很糟糕。 有办法解决吗?也许将标签放在查看区域的中间?

1 个答案:

答案 0 :(得分:2)

碰巧我们可以为每个vjust级别传递一个fill值,如

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

给予

enter image description here