树映射中的Squarify自动调整标签大小

2024-05-23 16:21:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Squarify在Python中实现一个简单的树映射

我正在绘制艺术家的名字,在考虑过的歌曲图表中,它的流的百分比,正方形越大/越暗,值就越高

我的代码如下:

dataGoals = sort_by_streams[sort_by_streams["Streams"]>1]

#Utilise matplotlib to scale our stream number between the min and max, then assign this scale to our values.
norm = matplotlib.colors.Normalize(vmin=min(dataGoals.Streams), vmax=max(dataGoals.Streams))
colors = [matplotlib.cm.Blues(norm(value)) for value in dataGoals.Streams]

#Create our plot and resize it.
fig1 = plt.figure()
ax = fig1.add_subplot()
fig1.set_size_inches(16, 4.5)

#Use squarify to plot our data, label it and add colours. We add an alpha layer to ensure black labels show through
labels = ["%s\n%.2f" % (label) for label in zip(dataGoals.Artist, dataGoals.Streams)]

squarify.plot(label=labels,sizes=dataGoals.Streams, color = colors, alpha=.7, bar_kwargs=dict(linewidth=0.5, edgecolor="#222222"),text_kwargs={'fontsize':15})
plt.title("Streams Percentage",fontsize=23,fontweight="bold")

#Remove our axes and display the plot
plt.axis('off')
plt.show()

这就是结果:

Treemap

正如您可能注意到的,较小正方形的标签重叠并超出边界。 是否有一种方法可以自动调整标签的大小以适应正方形

EDIT:我尝试用以下代码实现matplotlib的自动换行功能:squarify.plot(label=labels,sizes=dataGoals.Streams, color = colors, alpha=.7, bar_kwargs=dict(linewidth=0.5, edgecolor="#222222"),text_kwargs={'fontsize':20, 'wrap':True})但这并不能解决我的问题,我的文本标签仍然超出了范围


Tags: andtoaddlabelsplotmatplotlibourplt