图例 r 中标签的附加文本

Additional text to labels in legend r

我是r的新手,我想知道是否有办法在图例的标签中添加一些额外的文本。对于我的情况,我想向图例的每个标签文本添加一些额外的 percentage 但我未能实现。我尝试使用 scale_fill_hue 但它没有用。

这是我的代码:

library(ggplot2)
library(tidyverse)

cv_states = read.csv("coronavirus_states.csv")
a <- cv_states %>%
  group_by(state) %>%
  summarise(total= sum(new_cases)) %>%
  mutate(pourcentage= total/sum(total)*100) 

  ggplot(a,aes(x=fct_reorder(state,pourcentage),y=pourcentage,fill=state))+
  geom_bar(stat = "identity", position = position_dodge(width=5))+
  scale_color_hue( labels = paste0( as.factor(a$state) , ' (', round(as.numeric(a$pourcentage) ,digits = 2), "%)"))+
  coord_flip()

这是我的照片:

除此之外,如果我使用scale_fill_manual,我需要自己上色55次,这是巨大的。我的目标只是让 ggplot2 根据自己的选择填充颜色,就像我将 fill=state 放在 ggplot 函数中一样,我只想添加一些百分比文本,例如 New York (22%) 其他州同理

如果您需要文件测试,可以在此处找到:https://gitlab.com/Schrodinger168/practice/-/tree/master#

如有任何帮助,我们将不胜感激!!提前致谢!!

您最好在数据整理时在 ggplot 调用之外准备数据。

library(ggplot2)
library(dplyr)
library(forcats)

cv_states = read.csv("coronavirus_states.csv")

a <- cv_states %>%
  group_by(state) %>%
  summarise(total = sum(new_cases)) %>%
  mutate(pourcentage = total/sum(total)*100,
         state_pc = paste0(state, " (", round(pourcentage, 0), "%)")) 

ggplot(a,aes(x = fct_reorder(state, pourcentage), y = pourcentage, fill = state_pc))+
  geom_bar(stat = "identity", position = position_dodge(width = 5))+
  coord_flip()