【问题标题】:How do I use a DataFrame to create a legend in matplotlib?如何使用 DataFrame 在 matplotlib 中创建图例?
【发布时间】:2020-03-27 21:38:46
【问题描述】:

我已经使用 squarify 创建了一个树形图,现在我尝试创建一个图例以在图表旁边的树形图中显示数据。

内置的图例函数没有生成我想要的图例(它当前正在显示我的数据框的第一列和每行的索引)所以我一直在尝试使用它但没有成功。我希望传说是:

SKU 数量(单位)

一个1

b 2

c 3

d 4

e 5

f 6

g 7

小时 20

import matplotlib as mpl
import squarify
import matplotlib.cm
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

#create figure
fig = plt.gcf()
fig.set_size_inches(16, 5)

#set data values
data = [['a',1],['b',2],['c',3],['d',4],['e',5],['f',6],['g',7],['h',20]]
data_slice = pd.DataFrame(data, columns=['Atom SKU Code','Total Volume'])

print(data_slice)

#create color set
norm = mpl.colors.Normalize(vmin=min(data_slice['Total Volume']), vmax=max(data_slice['Total Volume']))
colors = [mpl.cm.BuGn(norm(value)) for value in data_slice['Total Volume']]

#plot figure
ax1 = squarify.plot(label=data_slice['Atom SKU Code'], sizes=data_slice['Total Volume'], color=colors, alpha=.6)
plt.title("Volume by SKU (Units Sold)", fontsize=23, fontweight="bold")
plt.axis('off')
plt.legend(title='SKU Volume in Units', loc='center left',bbox_to_anchor=(1, 0.5),frameon=False)
plt.tight_layout()
plt.show()

【问题讨论】:

    标签: python pandas matplotlib data-visualization seaborn


    【解决方案1】:

    想出了一个方法来做到这一点。 我删除了标签并使用 plt.table 创建了我的图例版本。 还利用我创建的颜色使图例看起来更漂亮。

    picture: output with legend table

    def genereate_legend_table(ax,colors,no_of_skus_to_graph,data_slice):
    # ___________________________________________________________________________________
    # DESCRIPTION
    # This functions generates a legend table to be plotted with the treemap plots
    
    #------------------------------------------------------------------------------------
    # ARGUMENTS
    # ax: subplot axis where the table is to be plotted
    
    # colors: color list object generated by matplotlibs color library
    
    # no_of_skus_to_graph: how many skus are being represented in the tree map
    
    # data_slice: the data to be written in the table
    # ___________________________________________________________________________________
    # Create hex color list from normalized color object
    hex_list = []
    for n in range(len(colors)):
        hex_list.append(mpl.colors.to_hex(colors[n]))
    
    
    # Create table object on desired axis
    legend_table = ax.table(cellText=data_slice.values,
                              colLabels=data_slice.columns,
                              loc='right',
                              colLoc='right',
                              colWidths=[0.2, 0.2],
                              edges='')
    
    # Change table text color
    i = 0
    while i <= no_of_skus_to_graph - 1:
        legend_table[(i + 1, 0)].get_text().set_color(hex_list[i])
        legend_table[(i + 1, 1)].get_text().set_color(hex_list[i])
        s = '¥{:,.2f}'.format(float(legend_table[(i + 1, 1)].get_text().get_text()))
        legend_table[(i + 1, 1)].get_text().set_text(s)
        i = i + 1
    
    # Return table
    return legend_table
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多