ggplot绘图修改图例标题及图例取值标签的问题咨询
问题描述
我正在使用ggplot绘制图表,想要修改图例的标题以及图例上展示的取值标签,尝试了现有常用的修改方法均未生效。
示例数据集结构
structure(list(sold_date_yq = structure(c(2014.5, 2014.75, 2014.75, 2015, 2015, 2015.25, 2015.25, 2015.5, 2015.5, 2015.75, 2015.75, 2016, 2016, 2016.25, 2016.25, 2016.5), class = "yearqtr"), V_tour_update = c(1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0), average_sold_sqft = c(646.354142011834, 623.121985926505, 678.629387755102, 651.493616045845, 666.909525139665, 671.250383912249, 680.049114583333, 698.693468862584, 699.523971830986, 718.077661016949, 759.139753521127, 791.252619047619, 814.418133704735, 836.438735902256, 884.5826, 849.757720754717)), row.names = c(NA, -16L), groups = structure(list(sold_date_yq = structure(c(2014.5, 2014.75, 2015, 2015.25, 2015.5, 2015.75, 2016, 2016.25, 2016.5 ), class = "yearqtr"), .rows = structure(list(1L, 2:3, 4:5, 6:7, 8:9, 10:11, 12:13, 14:15, 16L), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), row.names = c(NA, 9L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", "data.frame"))
现有绘图代码
ggplot(a, aes(x=sold_date_yq, y=average_sold_sqft)) + geom_line(aes(color=as.factor(V_tour_update)), size = 1) + scale_x_yearqtr(format="%YQ%q",n=6) + scale_y_continuous(limits = c(300,1200))+ theme(legend.position="right")+ theme(plot.title = element_text(hjust = 0.5, size=10))+ theme_bw()+ theme(axis.text.x = element_text(angle = 90, vjust=0, hjust=1))+ theme(legend.position=c(0.8, 0.1))
需求说明
我希望能够同时修改图例的标题,以及将图例中默认显示的0和1替换为自定义的说明文本,当前代码生成的结果图如下:
解决方案
你之前的方法失效主要有两个原因:一是theme_bw()放在了自定义theme配置之后,会重置前面的主题参数;二是没有针对color对应的映射修改图例配置,你可以直接通过scale_color_discrete一步实现图例标题和标签的修改,修改后的参考代码如下:
library(ggplot2) library(zoo) ggplot(a, aes(x=sold_date_yq, y=average_sold_sqft)) + geom_line(aes(color=as.factor(V_tour_update)), size = 1) + scale_x_yearqtr(format="%YQ%q",n=6) + scale_y_continuous(limits = c(300,1200)) + # 修改图例标题和标签 scale_color_discrete( name = "替换为你需要的图例标题", labels = c("0对应的自定义说明", "1对应的自定义说明") ) + # 把theme_bw()放在所有自定义theme配置之前,避免覆盖自定义参数 theme_bw() + theme(axis.text.x = element_text(angle = 90, vjust=0, hjust=1)) + theme(legend.position=c(0.8, 0.1)) + theme(plot.title = element_text(hjust = 0.5, size=10))
如果你不想在scale里修改,也可以提前把字段转成自定义标签的因子:
# 提前转换因子并设置标签 a$V_tour_update <- factor(a$V_tour_update, levels = c(0,1), labels = c("0对应的自定义说明", "1对应的自定义说明")) # 绘图时直接映射,用labs修改图例标题 ggplot(a, aes(x=sold_date_yq, y=average_sold_sqft)) + geom_line(aes(color=V_tour_update), size = 1) + scale_x_yearqtr(format="%YQ%q",n=6) + scale_y_continuous(limits = c(300,1200)) + labs(color = "替换为你需要的图例标题") + theme_bw() + theme(axis.text.x = element_text(angle = 90, vjust=0, hjust=1)) + theme(legend.position=c(0.8, 0.1)) + theme(plot.title = element_text(hjust = 0.5, size=10))
两种方法都可以实现你的需求,按需选择即可。
内容的提问来源于stack exchange,提问作者Yellow_truffle
相关产品推荐
相关产品推荐

