【问题标题】:100% area plot of a pandas DataFramepandas DataFrame 的 100% 面积图
【发布时间】:2015-04-29 10:00:58
【问题描述】:

pandas' documentation 中,您可以找到关于面积图 的讨论,尤其是堆叠它们。有没有一种简单直接的方法来获得像这样的 100% 面积堆栈图

来自this post

【问题讨论】:

    标签: python pandas plot


    【解决方案1】:

    方法与the other SO answer中的方法基本相同;将每一行除以行的总和:

    df = df.divide(df.sum(axis=1), axis=0)
    

    然后你可以像往常一样拨打df.plot(kind='area', stacked=True, ...)


    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    np.random.seed(2015)
    
    y = np.random.randint(5, 50, (10,3))
    x = np.arange(10)
    df = pd.DataFrame(y, index=x)
    
    df = df.divide(df.sum(axis=1), axis=0)
    ax = df.plot(kind='area', stacked=True, title='100 % stacked area chart')
    
    ax.set_ylabel('Percent (%)')
    ax.margins(0, 0) # Set margins to avoid "whitespace"
    
    plt.show()
    

    产量

    【讨论】:

    • 另一种可能是pandas.DataFrame.plot.area()
    • ax.margins(0, 0) 很脆弱,经常无法按预期工作。 ax.autoscale(enable=True, axis='both', tight=True) 在现代 matplotlib 中更好。
    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 2013-05-28
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多