R语言Plotly使用subplot拼接时如何保留子图独立标题与y轴标题
问题原因
plotly的subplot()默认会覆盖子图的布局配置,你在style()中传入的title/titleY不属于trace(图元)样式控制参数,本身是无效的,因此会出现子图标题、坐标轴标题丢失的问题。
可行方案
通过subplot()原生支持的参数配置轴标题保留、子图标题传入,不要在style()中处理布局类配置,可直接运行以下代码实现需求:
library(dplyr) library(plotly) # 测试数据集 df<-data.frame( Years = rep(2010:2020,len=22), Tax = rep(c("PIT","CIT","VAT"),22), Revenues = rep(c(200,400,100),22) ) df$Pct<-prop.table(df$Revenues) # 逐个定义子图,仅保留独立轴配置,不单独设置子图标题、全局图例 gen_subplot <- function() { plot_ly(df, x = ~Years, y = ~Pct, type = 'bar', marker = list(color = ~Revenues), name = ~Tax) %>% layout(yaxis = list(title = 'Percentage %'), barmode = 'stack') } p1 <- gen_subplot() p2 <- gen_subplot() p3 <- gen_subplot() p4 <- gen_subplot() # 拼接子图 final_plot <- subplot( p1, p2, p3, p4, nrows = 2, margin = 0.08, titleY = TRUE, # 全局开启y轴标题显示 titleX = TRUE, # 全局开启x轴标题显示,默认仅最下方子图展示x轴标签 subplot_titles = c("AA", "BB", "CC", "DD") # 按子图顺序传入独立标题 ) %>% layout(legend = list(orientation = 'h')) # 统一配置横向图例,仅展示一次 final_plot
配置说明
- 若需要隐藏部分子图的轴标题,直接在定义对应子图时将对应轴的
title设为空字符串即可,例如不需要上方两个子图的x轴标题,就在p1、p2的layout中加xaxis = list(title = "")。 - 若需要调整子图标题的字号、位置,可在后续
layout()中修改annotations参数对应配置。 style()函数仅支持修改图元的样式属性,所有标题、坐标轴、图例这类布局层面的配置,都要在layout()或subplot()的专属参数中设置,写在style()里不会生效。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

