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

Plotly词云优化:如何让文字居中且不超出绘图区域

解决Plotly词云文字超出绘图区域的问题

你的代码里文字超出绘图区域,主要是因为随机生成的坐标点太靠近边界,加上文字本身有尺寸,导致边缘被裁剪。下面提供几个实用的解决方案:

方法一:让坐标点集中在中心区域

把随机坐标的生成范围从[0,1]调整到靠近中心的区间,同时设置坐标轴的范围,给文字留出足够的边界空间:

import plotly
import random
import plotly.graph_objects as go

random.seed(42) 

words = ['potato','hello','juvi']
# 颜色数量匹配词的数量更合理,也可保留原20个不影响功能
colors = [plotly.colors.DEFAULT_PLOTLY_COLORS[random.randrange(1, 10)] for _ in range(len(words))]
weights = [110,80,20]

# 生成[-0.4, 0.4]范围内的坐标,集中在中心
data = go.Scatter(
    x=[(random.random() - 0.5) * 0.8 for _ in range(len(words))],
    y=[(random.random() - 0.5) * 0.8 for _ in range(len(words))],
    mode='text',
    text=words,
    marker={'opacity': 0.3},
    textfont={'size': weights, 'color': colors}
)

# 设置坐标轴范围为[-1,1],给文字留出边界
layout = go.Layout(
    xaxis={'showgrid': False, 'showticklabels': False, 'zeroline': False, 'range': [-1, 1]},
    yaxis={'showgrid': False, 'showticklabels': False, 'zeroline': False, 'range': [-1, 1]}
)
fig = go.Figure(data=[data], layout=layout)
fig.show()

方法二:添加布局边距并固定文字对齐

通过设置textposition确保文字中心对齐坐标点,再给布局添加边距,避免文字被绘图区域边缘裁剪:

import plotly
import random
import plotly.graph_objects as go

random.seed(42) 

words = ['potato','hello','juvi']
colors = [plotly.colors.DEFAULT_PLOTLY_COLORS[random.randrange(1, 10)] for _ in range(len(words))]
weights = [110,80,20]

data = go.Scatter(
    x=[random.random() for _ in range(len(words))],
    y=[random.random() for _ in range(len(words))],
    mode='text',
    text=words,
    marker={'opacity': 0.3},
    textfont={'size': weights, 'color': colors},
    textposition='center'  # 强制文字中心对齐坐标点
)

layout = go.Layout(
    xaxis={'showgrid': False, 'showticklabels': False, 'zeroline': False, 'range': [0, 1]},
    yaxis={'showgrid': False, 'showticklabels': False, 'zeroline': False, 'range': [0, 1]},
    margin=dict(l=50, r=50, t=50, b=50)  # 上下左右添加50px边距
)
fig = go.Figure(data=[data], layout=layout)
fig.show()

补充说明

如果你的词云有大量不同尺寸的文字,还可以根据最大文字的尺寸动态计算坐标轴范围,不过上面两种方法已经能解决绝大多数场景的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 22:12:43