如何使用matplotlib创建堆叠线图?

时间:2010-02-09 00:51:39

标签: python matplotlib

我希望能够使用Python生成堆叠线图(类似于使用的方法here)(最好使用matplotlib,但另一个库也可以。)我怎么能这样做?

这类似于他们网站上的stacked bar graph example,除了我希望条形图的顶部与线段连接并且下面的区域要填充。我可以通过减少条形之间的间隙和使用大量条形来近似这个(但这看起来像是一个黑客,而且我不确定它是否可能)。

4 个答案:

答案 0 :(得分:55)

较新版本的matplotlib包含函数plt.stackplot,它允许使用几个不同的“开箱即用”堆积区域图:

import numpy as np
import pylab as plt

X = np.arange(0, 10, 1) 
Y = X + 5 * np.random.random((5, X.size))

baseline = ["zero", "sym", "wiggle", "weighted_wiggle"]
for n, v in enumerate(baseline):
    plt.subplot(2 ,2, n + 1)
    plt.stackplot(X, *Y, baseline=v)
    plt.title(v)
    plt.axis('tight')
plt.show()

Stack Plot using plt.stackplot.

答案 1 :(得分:48)

我认为 Area Plot 是此类情节的常用术语,并且在OP中列出的具体实例中, 堆积区域图 即可。

Matplotlib没有“开箱即用”的功能,它结合了两个数据处理和绘图/渲染步骤来创建这种类型的情节,但它很容易滚动你的拥有Matplotlib和NumPy提供的组件。

下面的代码首先 堆叠 数据,然后 绘制 图。

import numpy as NP
from matplotlib import pyplot as PLT

# just create some random data
fnx = lambda : NP.random.randint(3, 10, 10)
y = NP.row_stack((fnx(), fnx(), fnx()))   
# this call to 'cumsum' (cumulative sum), passing in your y data, 
# is necessary to avoid having to manually order the datasets
x = NP.arange(10) 
y_stack = NP.cumsum(y, axis=0)   # a 3x10 array

fig = PLT.figure()
ax1 = fig.add_subplot(111)

ax1.fill_between(x, 0, y_stack[0,:], facecolor="#CC6666", alpha=.7)
ax1.fill_between(x, y_stack[0,:], y_stack[1,:], facecolor="#1DACD6", alpha=.7)
ax1.fill_between(x, y_stack[1,:], y_stack[2,:], facecolor="#6E5160")

PLT.show()

example of stacked area plot

答案 2 :(得分:7)

稍微不那么强硬的方法是首先使用折线图和matplotlib.pyplot.fill_between。为了模拟堆叠,你必须自己移动点。

x = np.arange(0,4)
y1 = np.array([1,2,4,3])
y2 = np.array([5,2,1,3])
# y2 should go on top, so shift them up
y2s = y1+y2

plot(x,y1)
plot(x,y2s)
fill_between(x,y1,0,color='blue')
fill_between(x,y1,y2s,color='red')

答案 3 :(得分:6)

如果您有数据框,那很简单:

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot.area();

enter image description here

来自:pandas documentation