You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在plot_ly树形图中左对齐标题?及相关函数咨询

解答

1. 标题左对齐的设置方法

在layout()的title参数列表中添加x = 0(将标题水平位置固定在最左侧)和xanchor = 'left'(确保标题以左侧为锚点对齐)即可实现左对齐效果。修改后的完整代码如下:

df_plotly <- plot_ly(
  df_konk_cum_tot,
  labels = ~ SNI2007,
  parents = NA,
  values = ~ sum_anstallda,
  type = 'treemap',
  hovertemplate = "Bransch: %{label}<br>Anställda: %{value}<extra></extra>") %>%
  layout(title = list(text = paste0('Anställda berörda av konkurser, kumulativt',
                                    '<br>',
                                    '<sup>',
                                    sprintf("%s - till och med ", geografi),'</sup>'),
                      x = 0,  # 固定标题到最左侧
                      xanchor = 'left'),  # 以左侧为锚点保证对齐
         margin = list(l = 0, r = 0, b = 0, t = 70))

df_plotly

如果需要调整标题与左侧边缘的间距,可在title列表中追加pad = list(l = 10)(数值可按需修改)来设置左侧内边距。

2. 更简洁的Plotly树形图创建函数

Plotly官方推荐使用Plotly Express的px.treemap()函数,它是更现代、语法更简洁的树形图生成方式,无需手动拼接plot_ly()与layout(),还能轻松处理多层级结构。示例代码如下:

library(plotly)

df_plotly_express <- px.treemap(df_konk_cum_tot,
                                path = ~SNI2007,  # 对应原代码的labels参数
                                values = ~sum_anstallda,
                                title = paste0('Anställda berörda av konkurser, kumulativt',
                                              '<br>',
                                              '<sup>',
                                              sprintf("%s - till och med ", geografi),'</sup>'),
                                hover_data = list(sum_anstallda = ':.0f'))  # 自定义hover数值格式

# 同样设置标题左对齐
df_plotly_express <- df_plotly_express %>%
  layout(title = list(x = 0, xanchor = 'left'),
         margin = list(l = 0, r = 0, b = 0, t = 70))

df_plotly_express

px.treemap()支持直接通过path参数传入多个变量生成多层级树形图,同时内置了更便捷的hover数据、颜色映射等配置,是当前创建Plotly树形图的首选方式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:09:59