我正在使用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()
这是结果:
您可能会注意到,较小方块的标签重叠并超出边界。有没有办法自动调整标签大小以适合正方形?
编辑:我尝试使用以下代码实现 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})
但这并不能解决我的问题,我的文本标签仍然超出范围。