我是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()