import plotly
import random
import plotly.graph_objects as go
from plotly.subplots import make_subplots
random.seed(42)
words = ['potato','hello','juvi']
colors = [plotly.colors.DEFAULT_PLOTLY_COLORS[random.randrange(1, 10)] for i in range(20)]
weights = [110,80,20]
data = go.Scatter(x=[random.random() for i in range(20)],
y=[random.random() for i in range(20)],
mode='text',
text=words,
marker={'opacity': 0.3},
textfont={'size': weights,
'color': colors})
layout = go.Layout({'xaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False},
'yaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False}})
fig = go.Figure(data=[data], layout=layout)
fig.show()
我有以下示例代码,它可以在绘图中生成词云,事情是,正如您所看到的,这些单词往往会超出图中给定的方块,关于如何将单词保留在蓝色方块内的任何想法。或者至少更靠近它的中心
发生这种情况是因为您将 20 个随机生成的 (x,y) 坐标传递给
go.Scatter
,但总共只有 3 个单词,因此绘图是根据您传递的坐标而不是位置来设置默认轴范围这 3 个字。
如果这不是故意的,那么我会假设您打算在 20 个坐标处从列表中随机选择 20 个单词,然后您将像这样修改代码:
import plotly
import random
import plotly.graph_objects as go
from plotly.subplots import make_subplots
random.seed(42)
words = ['potato','hello','juvi']
colors = [plotly.colors.DEFAULT_PLOTLY_COLORS[random.randrange(1, 10)] for i in range(20)]
weights = [110,80,20]
x = [random.random() for i in range(20)]
y = [random.random() for i in range(20)]
scatter_words = [random.choice(words) for i in range(20)]
scatter_weights = [random.choice(weights) for i in range(20)]
data = go.Scatter(x=x,
y=y,
mode='text',
text=scatter_words,
marker={'opacity': 0.3},
textfont={'size': scatter_weights,
'color': colors})
layout = go.Layout({'xaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False},
'yaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False}})
fig = go.Figure(data=[data], layout=layout)
fig.show()