繁体   English   中英

如何在 ggplot2 中的每个组的底部添加 geom_text 标签

[英]how to add geom_text labels at the bottom of each group in ggplot2

我正在尝试在每个分组条下方添加日期,即在 y 轴的 0 和 x 轴的产品标签之间。 列出的是一个代表。

df1 <- data.frame(product = c("A","A","A","A","A","A","A","B","B","B","B","B","B","B","C","C","C","C","C","C","C","D","D","D","D","D","D","D"), 
                  start_date =as.Date(c('2020-02-01', '2020-02-02', '2020-02-03', '2020-02-04', '2020-02-05', '2020-02-06', '2020-02-07')),
                  value = c(15.71,17.37,19.93,14.28,15.85,10.5,8.58,5.62,5.19,5.44,4.6,7.04,6.29,3.3,20.35,27.92,23.07,12.83,22.28,21.32,31.46,34.82,23.68,29.11,14.48,25.2,16.91,27.79))

graph <- ggplot(df1, aes(y = value, x = product, fill = product, group = factor(start_date))) +
  geom_col(data = df1, stat = "identity",position = position_dodge(width = 0.8), width = 0.7, inherit.aes = TRUE, size = 0) + 
  geom_text(aes(label= format(as.Date(start_date,format="%Y-%m-%d"), format = "%d")), vjust = "bottom", position = position_dodge(width = 0.8), inherit.aes = TRUE) +
  xlab("Product") + ylab("Values") 

即使我调整 vjust 或 hjust 值,我也会得到以下 plot 在此处输入图像描述

我想要类似于下面的 plot 的日期在此处输入图像描述

您几乎拥有它,但关键是要意识到所有文本都具有相同的 y 值:在这种情况下,它略低于 0。这有效:

graph <- ggplot(df1, aes(y = value, x = product, fill = product, group = factor(start_date))) +
    geom_col(position = position_dodge(width = 0.8),
        width = 0.7, inherit.aes = TRUE, size = 0) +
    geom_text(aes(
            label= format(as.Date(start_date,format="%Y-%m-%d"), format = "%d"),
            y=-0.5
        ),
        position = position_dodge(width = 0.8), size=2) +
    xlab("Product") + ylab("Values")

在此处输入图像描述

另请注意,我在这里和那里删除了不需要的位,因为它们是继承的:(1) data= call for geom_col ,和 (2) stat= call for geom_col

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM