You need to enable JavaScript to run this app. 如何调整column()内Plotly图表的标题对齐方式及与图表的间距
优惠活动
大模型
产品
解决方案
定价
更多

如何调整column()内Plotly图表的标题对齐方式及与图表的间距

两个需求都可以通过调整plotly的layout配置实现:

  • 标题左对齐:将原layout中的title参数从纯字符串改为列表结构,设置x = 0即可实现完全左对齐,默认值0.5为居中对齐
  • 调整标题与图表间距:在title列表中添加pad参数,通过b字段控制标题底部与图表顶部的间距,数值越大间距越大,也可配合全局margin参数的t字段调整图表整体顶部边距,避免标题被截断

修改后的完整可运行代码如下:

library(shiny)
library(plotly)
library(shinydashboard)
x <- c('Product A', 'Product B', 'Product C')
y <- c(20, 14, 23)
text <- c('27% market share', '24% market share', '19% market share')
data <- data.frame(x, y, text)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
     column(4,
            plotlyOutput("plot"))
      ),
    
  )
)

server <- function(input, output) { 
  output$plot<-renderPlotly({
    fig <- plot_ly(data, x = ~x, y = ~y, type = 'bar',
                   text = y, textposition = 'outside',
                   # rotate label
                   textangle = 90,
                   marker = list(color = 'rgb(158,202,225)',
                                 line = list(color = 'rgb(8,48,107)', width = 1.5)))
    fig <- fig %>% layout(
      title = list(
        text = paste("Cumulative Uptake (%) of the first vaccine dose among adults (18+) in EU/EEA countries","as of 2021-04-05",sep="\n"),
        x = 0, # 左对齐配置
        pad = list(b = 15) # 标题底部和图表的间距,可自行调整数值
      ),
      titlefont = list(size = 12),
      margin = list(t = 70), # 图表整体顶部边距,可根据标题长度自行调整
      xaxis = list(fixedrange=T, title = ""),
      yaxis = list(fixedrange=T,title = ""))
    
    fig
  })
}

shinyApp(ui, server)

内容的提问来源于stack exchange,提问作者firmo23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 05:06:03