如何调整ggplot中Y轴标题的行间距?含ggsave导出异常问题
ggplot导出时Y轴标题行间距异常的解决方法
问题描述
用ggplot绘图时,通过以下代码实现Y轴标题换行:
labs(y = paste0("Mean Precipitation Height across all days and all years"))
发现直接打印图表时Y轴标题行间距正常,但使用ggsave()导出图片时,行间距会异常增大,需要缩小换行后的行间距。
解决方法
在theme()中为axis.title.y添加lineheight参数即可解决:
theme(axis.title.y = element_text(lineheight = 1))
可复现代码(已包含修复方案)
library(tidyverse) library(here) { set.seed(123) index = rep(c(1:10), each = 100) ; year = rep(c(1951:1960), each = 10, times = 10); month = rep(c(1:10), each = 1, times = 100) variable_of_interest = runif(1000, min = 0, max = 0.4); season = rep(x = c("Winter", "Winter", "Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "Autmn", "Autmn"), times = 100) lat = rep(c(seq(from = 48, to = 53, length = 10)), each = 100); lon = rep(c(seq(from = 7, to = 14, length = 10)), each = 100) Variable_of_Interest = as.data.frame(cbind(index, year, month, variable_of_interest, season, lat, lon)) Variable_of_Interest$month_of_year = paste0(Variable_of_Interest$year, "-", Variable_of_Interest$month) rownames(Variable_of_Interest) = NULL # 转换列为数值型 Variable_of_Interest = mutate_at(Variable_of_Interest, c(1,2,3,4,6,7), as.numeric) } Spatial_Means = group_by(.data = Variable_of_Interest, lat, lon) %>% summarise(mean_variable_of_interest = mean(variable_of_interest)) Spatial_Means_per_Latitudinal_Degree = ggplot(Spatial_Means) + geom_point(aes(x = lat, y = mean_variable_of_interest), size = 1) + labs(title = "Latitudinal Means of Variable of Interest Across Time", x = "Latitude (degree)", y = paste0("Mean Variable of Interest across all days and all years")) + theme_bw() + theme(plot.title = element_text(hjust = 0.5, size = 40), axis.title.x = element_text(size = 20), axis.title.y = element_text(size = 20, lineheight = 1), # 此处添加行间距设置 axis.text.x = element_text(size = 20, face = "bold"), axis.text.y = element_text(size = 20, face = "bold")) ggsave(filename = "Spatial-Means-per-Latitudinal-Degree.JPG", plot = Spatial_Means_per_Latitudinal_Degree, path = here(), width = 10, height = 5)
内容的提问来源于stack exchange,提问作者RibbitRibbit
相关产品推荐
相关产品推荐

