代码之家  ›  专栏  ›  技术社区  ›  aviss

使用所有行作为基准线绘制交叉表结果

  •  1
  • aviss  · 技术社区  · 6 年前

    test = pd.DataFrame({'cluster':['1','1','1','1','2','2','2','2','2','3','3','3'],
                     'type':['a','b','c','a','a','b','c','c','a','b','c','a']})
    

    我使用交叉表生成新的数据帧并绘制结果:

    pd.crosstab(test.cluster,test.type,normalize='index',margins=True).plot(kind='bar')
    

    enter image description here

    我想把这一行全部画成虚线和水平基准线 同样的颜色 对应每种类型,以提高对绘图的解释。我们将感谢这个社区的帮助!

    1 回复  |  直到 6 年前
        1
  •  0
  •   unutbu    6 年前
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    test = pd.DataFrame(
        {'cluster': ['1', '1', '1', '1', '2', '2', '2', '2', '2', '3', '3', '3'],
         'type': ['a', 'b', 'c', 'a', 'a', 'b', 'c', 'c', 'a', 'b', 'c', 'a']})
    tab = pd.crosstab(test.cluster, test.type, normalize='index', margins=True)
    
    fig, ax = plt.subplots()
    
    # find the default colors
    prop_cycle = plt.rcParams['axes.prop_cycle']
    colors = prop_cycle.by_key()['color']
    
    # make a bar plot using all rows but the last
    tab.iloc[:-1].plot(ax=ax, kind='bar', color=colors)
    
    # draw the horizontal dotted lines
    for y, c in zip(tab.loc['All'], colors):
        ax.axhline(y=y, color=c, linestyle=':', alpha=0.5)
    plt.show()
    

    enter image description here