如何在 python 的 Pareto Chart 中添加 vital few?

How to add vital few to Pareto Chart in python?

我用的是卓尔

这个代码
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    data = pd.DataFrame({"Type of defect":["A","B","C","D","E","F","G","Other"], "Count":[17,202,387,25,825,12,3,45]})
    data=data.set_index("Type of defect")
    data = pd.concat([data[data.index!='Other'].sort_values(by='Count',ascending = False), data[data.index=='Прочее']])
    data['Accumulated frequency'] = 100 *data['Count'].cumsum() / data['Count'].sum()
    data['Limit']=80
    data['Vital few']=np.where((data['Limit'] <= data['Accumulated frequency']) & (data['Limit'].shift(1) <= data['Accumulated frequency'].shift(1)), 0, 100)
    fig, axes = plt.subplots()
    ax1 = data.plot(use_index=True, y='Count',  kind='bar', ax=axes)
    ax2 = data.plot(use_index=True, y='Accumulated frequency', marker='D', color="C1", kind='line', ax=axes, secondary_y=True)
    ax2.set_ylim([0,110])
    ax3 = data.plot(use_index=True, y='Limit', color="gray", kind='line', linestyle='dashed', ax=axes, secondary_y=True)
    ax4 = data.plot(use_index=True, y='Vital few', color="yellow", kind='area', ax=axes, secondary_y=True, alpha=0.1)

我得到 following picture 但是,我需要得到 this chart

主要问题是如何显示“vital few”(黄色区域)。图例和 row/column 标签的位置也存在问题。请帮我解决这个问题。

面积图无法绘制矩形,需要使用matplotlib的axvspan()。 axvspan()在图例中没有体现,需要添加,使用Patch设置矩形和标签。

from matplotlib.patches import Patch

fig, axes = plt.subplots()

ax1 = data.plot(use_index=True, y='Count',  kind='bar', ax=axes)
ax2 = data.plot(use_index=True, y='Accumulated frequency', marker='D', color="C1", kind='line', ax=axes, secondary_y=True)
ax2.set_ylim([0,110])
ax3 = data.plot(use_index=True, y='Limit', color="gray", kind='line', linestyle='dashed', ax=axes, secondary_y=True)
#ax4 = data.plot(use_index=True, y='Vital few', color="yellow", kind='area', ax=axes, secondary_y=True, alpha=0.1)
axes.axvspan(-0.5,1.25, ymax=0.95,facecolor='yellow', alpha=0.1)

handler1, label1 = ax1.get_legend_handles_labels()
#handler2, label2 = ax2.get_legend_handles_labels()
handler3, label3 = ax3.get_legend_handles_labels()
#print(label1, label2, label3)

add_legend = [Patch(facecolor='yellow', edgecolor='yellow', alpha=0.1, label='Vital few(right)')]
axes.legend(handles=handler1+handler3+add_legend)
plt.show()

编辑: 如果它严格链接到 y-axis 值,则可以通过条形图作为替代方法来处理。通过增加默认宽度,条形将被连接起来。

ax4 = data.plot(use_index=True, y='Vital few',color='yellow', kind='bar', width=1.0,ax=axes, secondary_y=True, alpha=0.1)