【发布时间】:2015-04-29 10:00:58
【问题描述】:
在pandas' documentation 中,您可以找到关于面积图 的讨论,尤其是堆叠它们。有没有一种简单直接的方法来获得像这样的 100% 面积堆栈图
来自this post?
【问题讨论】:
在pandas' documentation 中,您可以找到关于面积图 的讨论,尤其是堆叠它们。有没有一种简单直接的方法来获得像这样的 100% 面积堆栈图
来自this post?
【问题讨论】:
方法与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 中更好。