我无法让 label=sprintf 强制我的标签显示小数点后两位

I can't get label=sprintf to force my labels to show 2 decimal places

我有以下数据框:

Q <- data.frame("PERC" = c(1.1, 2.1, 8.3, 7.0, 9.8, 3.1, 4.1, 11.3,
                           9.0, 3.0, 4.0, 11.0, 1.1, 2.1, 8.3, 7.0,
                           9.0, 3.0, 8.3, 7.0),
           "Corp" = c("Aus", "China" ,"Aus", "China", "Aus", "China", 
                      "Aus", "China", "Aus", "China" ,"Aus", "China",
                      "Aus", "China" ,"Aus", "China", 
                      "Aus", "China" ,"Aus", "China"),
           "Journal" = c("O", "O", "G", "G", "O", "O", "G", "G",
                         "O", "O", "G", "G", "O", "O", "G", "G", 
                         "O", "O", "G", "G"),
           "Year" = c("2014", "2014", "2014", "2014", "2015", 
                      "2015", "2015", "2015",
                      "2016", "2016", "2016", "2016",
                      "2017", "2017", "2017", "2017",
                      "2018", "2018", "2018", "2018"),
           "lbl" = c(NA, "n = 60", NA, "n = 62", NA, "n = 70",
                     NA, "n = 93", NA, "n = 78", NA, "n = 26",
                     NA, "n = 2010", NA, "n = 30", 
                     NA, "n = 2014", NA, "n = 99")) 

当我尝试绘制以下图时,即使我在 aes 中使用 label=sprintf,我也无法得到显示“.0”的图形,例如 [=17] =]11.0, 3.07.0 它只显示 11, 37。有人可以指出我做错了什么吗?

ggplot(data = Q, mapping = aes(Year, PERC, label=sprintf("%0.2f", round(PERC, digits = 2)),
                               fill = Corp))+
  geom_col(position = "stack", alpha = 1, width = 0.9)+
  facet_wrap(~Journal)+
  geom_text(aes(label=PERC), colour = "Black", 
            position = position_stack(vjust = 0.5), size = 3.5)+
  xlab("\nPublished Year") + 
  ylab("Measured amount/Total amount (%)\n")+
  scale_y_continuous(breaks = seq(0, 13, by = 1), expand = c(0.1, 0)) +
  scale_fill_manual(values = c("#E69F00", "#0072B2", "#E69F00","#0072B2"),
                    labels = c("Australia",
                               "China"))+
  theme_bw()+
  theme(legend.position = "top", legend.title = element_blank())+
  geom_text(aes(label = lbl), y = -0.5)

当您已经在 aes 中定义标签时,它们会在 geom_text 中再次被覆盖。尝试:

library(ggplot2)

ggplot(data = Q, mapping = aes(Year, PERC, 
       label=sprintf("%0.2f", round(PERC, digits = 2)),
                               fill = Corp))+
  geom_col(position = "stack", alpha = 1, width = 0.9)+
  facet_wrap(~Journal)+
  geom_text(colour = "Black", 
            position = position_stack(vjust = 0.5), size = 3.5)+
  xlab("\nPublished Year") + 
  ylab("Measured amount/Total amount (%)\n")+
  scale_y_continuous(breaks = seq(0, 13, by = 1), expand = c(0.1, 0)) +
  scale_fill_manual(values = c("#E69F00", "#0072B2", "#E69F00","#0072B2"),
                    labels = c("Australia",
                               "China"))+
  theme_bw()+
  theme(legend.position = "top", legend.title = element_blank())+
  geom_text(aes(label = lbl), y = -0.5)