[英]Additional text to labels in legend r
我是 r 的新手,我想知道是否有办法在传说中的 label 中添加一些额外的文本。 对于我的情况,我想为图例的每个 label 文本添加一些额外的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
通过它的选择填充 colors,就像我将fill=state
放入ggplot
function 和我只想添加一些类似纽约州的百分比一样(例如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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.