簡體   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