在matplotlib中实现水平图

Pau*_*l H 10 python matplotlib

我正在尝试在matplotlib中实现水平图表(参见:http://square.github.com/cubism/ )

基本的想法是你以窄纵横比显示时间序列,随着值的增加(超过y轴限制),它们从底部开始以较暗的颜色开始(当你去的时候想想旧的Atari游戏)超过屏幕顶部并弹出底部).

我的基本方法是将y数据划分为卡盘并使用新的轴绘制每个垂直组ax.twinx()并适当设置限制.

仅对于正面或负面数据,这似乎运作良好.

正:

积极的地平线图

负:

负条形图

但出于某种原因,做两个螺丝:

# setup the environment
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, np.pi*4, 137)
y = (2*np.random.normal(size=137) + x**2)

# reflect everything around the origin
xx = np.hstack([-1*x[::-1], x])
yy = np.hstack([-1*y[::-1], y])

# function to do the plot
def horizonPlot(ax, x, y, nfolds=3, inverty=False, color='CornflowerBlue'):
    axes = [ax]
    if inverty:
        ylims = np.linspace(y.min(), y.max(), nfolds + 1)[::-1]
    else:
        ylims = np.linspace(y.min(), y.max(), nfolds + 1)

    for n in range(1, nfolds):
        newax = axes[-1].twinx()
        axes.append(newax)

    for n, ax in enumerate(axes):        
        ax.fill_between(x, y, y2=ylims[n], facecolor=color, alpha=1.0/nfolds, zorder=n)
        ax.set_ylim([ylims[n], ylims[n+1]])
        ax.set_yticklabels([])
        ax.set_yticks([])

        if inverty:
            ax.invert_yaxis()

    ax.set_xlim([x.min(), x.max()])
    return fig

fig, baseax = plt.subplots(figsize=(6.5,1.5))
posax = baseax.twinx()
negax = posax.twinx()
fig = horizonPlot(posax, xx, np.ma.masked_less(yy, 0), inverty=False, color='DarkGreen')
fig = horizonPlot(negax, xx, np.ma.masked_greater(yy, 0), inverty=True,   color='CornflowerBlue')
for ax in fig.get_axes():
    ax.set_yticklabels([])

fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

糟糕的图表(注意正面缺少多层):

两个水平图表

任何想法将不胜感激!

Mil*_*ell 5

我实际上不知道,为什么你的不工作,因为在我的电脑上工作正常.但是因为我对这个绘图真的很感兴趣,所以我试图在没有这些花哨的twinx东西的情况下自己实现它.

我只是将这些区域绘制在彼此之上,因为这实际上是关于情节的伟大事情.因此我不需要调整alpha,他们只是加起来.

import numpy as np
from matplotlib.pyplot import *

def layer(y,height):
    neg=0.0;pos=0.0
    if y>0:
        if y-height>=0:
            pos=height
            y-= pos
        else : 
            pos = y
    elif y<0:
        if y+height<=0:
            neg=height
            y += neg
        else : 
            neg = -y
    return pos,neg

def horizonPlot(x,y,height=50.0,colors=['CornflowerBlue','DarkGreen']):
    alpha = .10
    vlayer = np.vectorize(layer)
    while (y != 0).any():
        l = vlayer(y,height)
        y -= l[0];y += l[1]
        fill_between(x,0,l[0],color=colors[0], alpha=alpha)
        fill_between(x,height-l[1],height,color=colors[1], alpha=alpha)

def main():
    x = np.linspace(0, np.pi*4, 137)
    y = (2*np.random.normal(size=137) + x**2)
    xx = np.hstack([-1*x[::-1], x])
    yy = np.hstack([-1*y[::-1], y])
    horizonPlot(xx,yy)
    show()
Run Code Online (Sandbox Code Playgroud)

这看起来像我的机器上的以下内容.希望它适用于你的,但我只是使用基本的绘图方法.

在此输入图像描述