R Shiny中使用bslib包设置主题时plot_ly函数失效怎么解决?
问题原因
thematic包的自动主题同步仅支持base R绘图、ggplot2、lattice三类图形输出。你使用ggplotly时是先基于ggplot2生成符合主题的图形,再转成plotly对象,所以能继承主题配置;但直接调用原生plot_ly生成的对象不会自动读取bslib的主题参数,因此适配失效。
修复方案
你可以在生成plot_ly对象时,手动读取当前bslib主题的配色、字体等参数,传给plotly的layout配置实现主题同步,修改后的完整代码如下:
library(shiny) library(plotly) library(bslib) library(ggplot2) thematic::thematic_shiny(font = "auto") ui <- fluidPage( theme = bs_theme(), fluidRow( column(6, plotlyOutput(outputId ="p_plotly",width = "100%", height ="100%") ), column(6, plotlyOutput(outputId ="p_ggplotly",width = "100%", height ="100%") ) ) ) server <- function(input, output) { bs_themer() # 实时获取当前主题参数 current_theme <- reactive({ bs_get_variables(theme = getCurrentTheme(), c("bg", "fg", "primary", "font-family-base")) }) output$p_plotly<-renderPlotly({ theme_val <- current_theme() iris %>% plot_ly(x=~Sepal.Length,y=~Sepal.Width, color = I(theme_val[["primary"]])) %>% layout( paper_bgcolor = theme_val[["bg"]], plot_bgcolor = theme_val[["bg"]], font = list(color = theme_val[["fg"]], family = theme_val[["font-family-base"]]), xaxis = list(color = theme_val[["fg"]], gridcolor = adjustcolor(theme_val[["fg"]], 0.2)), yaxis = list(color = theme_val[["fg"]], gridcolor = adjustcolor(theme_val[["fg"]], 0.2)) ) }) output$p_ggplotly<-renderPlotly({ plt<-ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+geom_point() ggplotly(plt) }) } shinyApp(ui, server)
补充说明
- 代码中通过
getCurrentTheme()实时读取当前生效的bslib主题参数,包括背景色、前景色、主色、字体 - 把对应的参数手动配置到plotly的画布、坐标轴、字体、网格线等元素上,即可实现和ggplotly一致的主题适配效果
- 如果需要适配更多主题样式,可以扩展
bs_get_variables的参数列表,读取更多主题变量后配置到plotly的对应属性即可
内容的提问来源于stack exchange,提问作者Masoud
相关产品推荐
相关产品推荐

