如何修改ggplot2柱状图的图例标签名称?
解决ggplot2图例标签替换问题
你刚接触R语言数据分析,用ggplot2绘制柱状图时,图例显示的mediaIntegralAmpla、mediaIntegralCotas、mediaParcialAmpla、mediaParcialCotas需要替换为“Integral ampla”“Integral cotas”“Parcial ampla”“Parcial cotas”,之前修改geom_bar参数和labs没成功,你的代码如下:
library(ggplot2) grafico.media <- ggplot(transposto, aes(x = areaDoConhecimento, y = media, fill = nome_media)) + geom_bar(stat = "identity", position = "dodge") + labs(title = "Média das notas de corte por Área do Conhecimento", x = "Área de Conhecimento", y = "Média das notas", fill = "Legenda") + theme_minimal() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + # rotaciona a legenda do eixo x scale_y_continuous(breaks = seq(0, 600, by = 200)) # Define intervalo de 500000 no eixo y print(grafico.media)
方法一:使用scale_fill_discrete()指定标签
直接在ggplot代码中添加scale_fill_discrete()函数,通过labels参数按顺序设置新的图例标签,确保和原标签一一对应:
library(ggplot2) grafico.media <- ggplot(transposto, aes(x = areaDoConhecimento, y = media, fill = nome_media)) + geom_bar(stat = "identity", position = "dodge") + labs(title = "Média das notas de corte por Área do Conhecimento", x = "Área de Conhecimento", y = "Média das notas", fill = "Legenda") + theme_minimal() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + scale_y_continuous(breaks = seq(0, 600, by = 200)) + # 添加这一行替换图例标签 scale_fill_discrete(labels = c("Integral ampla", "Integral cotas", "Parcial ampla", "Parcial cotas")) print(grafico.media)
方法二:提前修改数据中的因子水平
如果后续还会用到这个列绘图,建议直接修改transposto数据框中nome_media列的因子水平,这样所有基于该列的可视化都会自动使用新标签:
# 先修改数据框的因子水平 transposto$nome_media <- factor(transposto$nome_media, levels = c("mediaIntegralAmpla", "mediaIntegralCotas", "mediaParcialAmpla", "mediaParcialCotas"), labels = c("Integral ampla", "Integral cotas", "Parcial ampla", "Parcial cotas")) # 再绘制图表,无需额外设置图例标签 library(ggplot2) grafico.media <- ggplot(transposto, aes(x = areaDoConhecimento, y = media, fill = nome_media)) + geom_bar(stat = "identity", position = "dodge") + labs(title = "Média das notas de corte por Área do Conhecimento", x = "Área de Conhecimento", y = "Média das notas", fill = "Legenda") + theme_minimal() + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + scale_y_continuous(breaks = seq(0, 600, by = 200)) print(grafico.media)
注意:两种方法中,levels和labels的顺序必须严格对应原标签和新标签的顺序,否则会出现标签匹配错误。
内容的提问来源于stack exchange,提问作者Daniel Zanotti da Silva
相关产品推荐
相关产品推荐

