如何在ggplotly中统一设置所有分面子图的字体大小?
解决ggplotly分面图所有子图文本大小统一修改问题
问题场景
我用ggplot绘制了分面柱状图,代码如下:
library(ggplot2) library(ggplotly) f1 <- diamonds |> group_by(cut,clarity,color) |> count() |> group_by(cut) |> mutate(N=sum(n)) |> ggplot() + aes( x = cut, y = n, fill = cut ) + geom_col() + theme(legend.position = "none")+ coord_flip()+ facet_wrap(vars(clarity)) f1
尝试将其转为ggplotly对象并修改文本大小时,仅第一个子图生效,其余子图无变化:
ggplotly(f1)%>% layout(legend=list(font = list(size = 8)), xaxis = list(titlefont = list(size = 8), tickfont = list(size = 8)), yaxis = list(titlefont = list(size = 8), tickfont = list(size = 8)))
且代码需嵌入函数中使用,分面数量不固定,无法通过手动指定xaxis2、yaxis2这类方式适配。
解决方案
通过动态生成所有分面对应的轴配置,实现批量修改所有子图的文本大小:
library(ggplot2) library(ggplotly) library(purrr) # 生成原始ggplot分面图 f1 <- diamonds |> group_by(cut,clarity,color) |> count() |> group_by(cut) |> mutate(N=sum(n)) |> ggplot() + aes(x = cut, y = n, fill = cut) + geom_col() + theme(legend.position = "none")+ coord_flip()+ facet_wrap(vars(clarity)) # 转换为ggplotly对象 p <- ggplotly(f1) # 获取分面总数(自动适配任意数量的分面) facet_total <- length(p$x$layout$xaxis) # 批量生成所有x轴的文本配置 x_axis_settings <- map( set_names(1:facet_total, paste0("xaxis", 1:facet_total)), ~list(titlefont = list(size = 8), tickfont = list(size = 8)) ) # 批量生成所有y轴的文本配置 y_axis_settings <- map( set_names(1:facet_total, paste0("yaxis", 1:facet_total)), ~list(titlefont = list(size = 8), tickfont = list(size = 8)) ) # 应用所有配置到ggplotly对象 p |> layout( legend = list(font = list(size = 8)), !!!c(x_axis_settings, y_axis_settings) )
关键说明
set_names为每个轴配置命名为xaxis1、xaxis2...yaxis1、yaxis2,对应ggplotly分面图中各个子图的轴!!!用于将列表中的配置项展开为layout的参数,实现批量注入- 分面总数通过读取ggplotly对象的轴数量自动获取,无需手动指定,适配任意分面数量的场景
内容的提问来源于stack exchange,提问作者yuliaUU
相关产品推荐
相关产品推荐

