简体   繁体   English

使用matplotlib返回图的一部分

[英]Return a portion of a plot using matplotlib

I'm using SpanSelector but am trying to return a portion of the plot being modified by spanSelector. 我正在使用SpanSelector,但尝试返回由spanSelector修改的图的一部分。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector

fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(211, axisbg='#FFFFCC')

x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))

ax.plot(x, y, '-')
ax.set_ylim(-2,2)
ax.set_title('Press left mouse button and drag to test')

ax2 = fig.add_subplot(212, axisbg='#FFFFCC')
line2, = ax2.plot(x, y, '-')


def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x)-1, indmax)

    thisx = x[indmin:indmax]
    thisy = y[indmin:indmax]
    print thisy
    line2.set_data(thisx, thisy)
    ax2.set_xlim(thisx[0], thisx[-1])
    ax2.set_ylim(thisy.min(), thisy.max())
    fig.canvas.draw()

# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red') )

plt.show()

Right now I only can print this part of the code being selected right now, but I want to return it to be used as a variable to have statistics made from it later in my code. 现在,我只能打印当前选择的部分代码,但是我想将其返回用作变量,以便稍后在我的代码中进行统计。 Is this possible, or do I need to do any statistics calculations inside of the onselect function? 这是否可能,或者我需要在onselect函数内部进行任何统计计算吗?

You can define a new function: 您可以定义一个新函数:

def calc_stats(xs, ys):
    print 'doing the calculations'

and call this from within onselect : 并从onselect内调用它:

def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x)-1, indmax)

    thisx = x[indmin:indmax]
    thisy = y[indmin:indmax]
    calc_stats(thisx, thisy)
    line2.set_data(thisx, thisy)
    ax2.set_xlim(thisx[0], thisx[-1])
    ax2.set_ylim(thisy.min(), thisy.max())
    fig.canvas.draw()

Alternatively, you can store the result in a global dictionary.: 或者,您可以将结果存储在全局字典中。

coords = {}

def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x)-1, indmax)

    thisx = x[indmin:indmax]
    thisy = y[indmin:indmax]
    coords['x'] = thisx
    coords['y'] = thisy
    line2.set_data(thisx, thisy)
    ax2.set_xlim(thisx[0], thisx[-1])
    ax2.set_ylim(thisy.min(), thisy.max())
    fig.canvas.draw()

# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red') )

plt.show()

print 'working with x an y'
print coords['x'][:10]
print coords['y'][:10]

Modifying a global dict is not really good style. 修改全局dict并不是很好的样式。 This does the same but uses a class: 这样做相同,但是使用一个类:

class Onselect():

    def __init__(self):
        self.coords = {}

    def __call__(self, xmin, xmax):
        indmin, indmax = np.searchsorted(x, (xmin, xmax))
        indmax = min(len(x)-1, indmax)

        thisx = x[indmin:indmax]
        thisy = y[indmin:indmax]
        self.coords['x'] = thisx
        self.coords['y'] = thisy
        line2.set_data(thisx, thisy)
        ax2.set_xlim(thisx[0], thisx[-1])
        ax2.set_ylim(thisy.min(), thisy.max())
        fig.canvas.draw()

onselect = Onselect()

# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red') )

plt.show()

print 'working with x an y'
print onselect.coords['x'][:10]
print onselect.coords['y'][:10]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM