本文介绍了matplotlib仅以幻灯片形式显示一组10张图中的一个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组10张图.(基于X/Y对)(在此示例中仅为3)与在同一窗口中的所有图形相同,显示一个图形很容易.(见图片)

但是我还没有找到想要的解决方案:这10张图是来自频谱分析仪的数据,并显示了信号.

我要显示第一张图,删除或删除它,然后在同一窗口中显示第二张图.

然后下一步,将删除第二张图,并且将看到第三张图(依此类推)

那是我的代码:

从matplotlib中的

 导入pyplot作为plt将numpy导入为npdatei = ['./2450ATT0.csv','./2450ATT0-1.csv','./2450ATT0-2.csv']对于datei中的文件:x = np.genfromtxt(文件,usecols =(0),分隔符=';',解压= True)y = np.genfromtxt(文件,usecols =(1),delimiter =';',unpack = True,dtype = float)plt.xlim(2435,2465)ylim(-120,-20)plt.xlabel('Frequenz')plt.ylabel('Leistung')plt.plot(x/1000000,y,label = file)plt.show() 

你有什么主意吗?我也看过了plt.animate.但是我还没有找到带有这些建议的解决方案.

谢谢.安迪

解决方案

一个接一个地显示数据对我来说有点不符合人体工程学.另外,使用动画可能不是最佳解决方案.如果在检查了第二个数据集之后又想回到第一个数据集,该怎么办?

因此,我将实施一个允许在光谱之间来回移动的解决方案.

以下沙箱示例基于

上面的代码正在工作,并显示出它的样子.在您的特定情况下,您需要对其进行一些更改.我试图相应地修改您的代码,但是我当然不能保证它能正常工作.这段代码必须放在 __ main __ 部分的下方,PageSlider必须保持不变.

 将numpy导入为np从matplotlib导入pyplot作为pltdateien = ['./2450ATT0.csv','./2450ATT0-1.csv','./2450ATT0-2.csv']data_x = []data_y = []对于dateien中的datei:#请勿在python中调用变量文件",因为这是受保护的x = np.genfromtxt(datei,usecols =(0),delimiter =';',unpack = True)x = x/1000000.y = np.genfromtxt(datei,usecols =(1),delimiter =';',unpack = True,dtype = float)data_x.append(x)data_y.append(y)无花果,ax = plt.subplots()fig.subplots_adjust(bottom = 0.18)ax.set_xlim([2435,2465])ax.set_xlim([-120,20])ax.set_xlabel('Frequenz')ax.set_ylabel('Leistung')文字= ax.text(0.98,0.98,dateien [0],ha ="right",va ="top")行,= ax.plot(data_x [0],data_y [0],color ="b")ax_slider = fig.add_axes([0.1,0.05,0.8,0.04])滑块= PageSlider(ax_slider,'Page',len(dateien),activecolor ="orange")def update(val):我= int(slider.val)line.set_data(data_x [i],data_y [i])text.set_text(dateien [i])slide.on_changed(更新)plt.show() 


对于简单的动画,您宁愿使用 matplotlib.animation.FuncAnimation ,代码看起来像是

 将numpy导入为np从matplotlib导入pyplot作为pltdateien = ['./2450ATT0.csv','./2450ATT0-1.csv','./2450ATT0-2.csv']data_x = []data_y = []对于dateien中的datei:#不要在python中调用变量文件",这是受保护的单词x = np.genfromtxt(datei,usecols =(0),delimiter =';',unpack = True)x = x/1000000.y = np.genfromtxt(datei,usecols =(1),delimiter =';',unpack = True,dtype = float)data_x.append(x)data_y.append(y)无花果,ax = plt.subplots()fig.subplots_adjust(bottom = 0.18)ax.set_xlim([2435,2465])ax.set_xlim([-120,20])ax.set_xlabel('Frequenz')ax.set_ylabel('Leistung')行,= ax.plot(data_x [0],data_y [0],color ="b")def update(i):line.set_data(data_x [i],data_y [i])ani = matplotlib.animation.FuncAnimation(fig,update,帧= len(dateien),间隔= 200,blit = False,重复= True)plt.show() 

I have a set of 10 graphs. (based on X/Y-pairs) (In this example only 3)Displaying one graph is easy, same to all graphs in the same window.(See picture)

But I haven't found a solution for what I want :The 10 graphs are Data from a spectrum analyzer and are showing a signal.

I want to display the first graph, delete or remove it and display the 2nd graph in the same window.

Then next, the second graph will be removed and the 3rd shall be seen (and so on)

Thats my Code :

from matplotlib import pyplot as plt
import numpy as np

datei = ['./2450ATT0.csv','./2450ATT0-1.csv','./2450ATT0-2.csv']

for file in datei:
    x = np.genfromtxt(file, usecols =(0), delimiter=';', unpack=True)
    y = np.genfromtxt(file, usecols =(1), delimiter=';', unpack=True, dtype=float)

    plt.xlim(2435,2465)
    plt.ylim(-120,-20)
    plt.xlabel('Frequenz')
    plt.ylabel('Leistung')
    plt.plot(x/1000000,y, label=file)  
plt.show()

Do you have any idea ?I also have had a look at plt.animate. but I haven't found a solution with that suggestions.

Thank you.Andi

解决方案

Showing the data one after the other seems a bit unergonomic to me. Also using an animation might not be the best solution. What if after inspection of the second dataset you want to go back to the first?

I would therefore implement a solution which allows to go back and forth between the spectra.

The following sandbox example is based on a solution I have provided to a similar problem with images. It uses a discrete Slider to walk through the pages. Although it may seem a bit complicated on first sight, you do not really have to understand the PageSlider class in order to use it. Just look at the code down in the __main__ part.

import matplotlib.widgets
import matplotlib.patches
import mpl_toolkits.axes_grid1

class PageSlider(matplotlib.widgets.Slider):

    def __init__(self, ax, label, numpages = 10, valinit=0, valfmt='%1d', 
                 closedmin=True, closedmax=True,  
                 dragging=True, **kwargs):

        self.facecolor=kwargs.get('facecolor',"w")
        self.activecolor = kwargs.pop('activecolor',"b")
        self.fontsize = kwargs.pop('fontsize', 10)
        self.numpages = numpages

        super(PageSlider, self).__init__(ax, label, 0, numpages, 
                            valinit=valinit, valfmt=valfmt, **kwargs)

        self.poly.set_visible(False)
        self.vline.set_visible(False)
        self.pageRects = []
        for i in range(numpages):
            facecolor = self.activecolor if i==valinit else self.facecolor
            r  = matplotlib.patches.Rectangle((float(i)/numpages, 0), 1./numpages, 1, 
                                transform=ax.transAxes, facecolor=facecolor)
            ax.add_artist(r)
            self.pageRects.append(r)
            ax.text(float(i)/numpages+0.5/numpages, 0.5, str(i+1),  
                    ha="center", va="center", transform=ax.transAxes,
                    fontsize=self.fontsize)
        self.valtext.set_visible(False)

        divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax)
        bax = divider.append_axes("right", size="5%", pad=0.05)
        fax = divider.append_axes("right", size="5%", pad=0.05)
        self.button_back = matplotlib.widgets.Button(bax, label=ur'$\u25C0$', 
                        color=self.facecolor, hovercolor=self.activecolor)
        self.button_forward = matplotlib.widgets.Button(fax, label=ur'$\u25B6$', 
                        color=self.facecolor, hovercolor=self.activecolor)
        self.button_back.label.set_fontsize(self.fontsize)
        self.button_forward.label.set_fontsize(self.fontsize)
        self.button_back.on_clicked(self.backward)
        self.button_forward.on_clicked(self.forward)

    def _update(self, event):
        super(PageSlider, self)._update(event)
        i = int(self.val)
        if i >=self.valmax:
            return
        self._colorize(i)

    def _colorize(self, i):
        for j in range(self.numpages):
            self.pageRects[j].set_facecolor(self.facecolor)
        self.pageRects[i].set_facecolor(self.activecolor)

    def forward(self, event):
        current_i = int(self.val)
        i = current_i+1
        if (i < self.valmin) or (i >= self.valmax):
            return
        self.set_val(i)
        self._colorize(i)

    def backward(self, event):
        current_i = int(self.val)
        i = current_i-1
        if (i < self.valmin) or (i >= self.valmax):
            return
        self.set_val(i)
        self._colorize(i)


if __name__ == "__main__":
    import numpy as np
    from matplotlib import pyplot as plt


    num_pages = 10
    data = np.random.rand(700, num_pages)
    spec = np.linspace(-10,10, 700)

    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.18)
    ax.set_ylim([0.,1.6])
    line, = ax.plot(spec,data[:,0], color="b")

    ax_slider = fig.add_axes([0.1, 0.05, 0.8, 0.04])
    slider = PageSlider(ax_slider, 'Page', num_pages, activecolor="orange")

    def update(val):
        i = int(slider.val)
        line.set_ydata(data[:,i])

    slider.on_changed(update)

    plt.show()

The code above is working and shows how this would look like. In your specific case, you would need to change it a bit. I tried to adapt your code accordingly, but of course I cannot guarantee that it works. This code has to be put below the __main__ part, the PageSlider must stay unchanged.

import numpy as np
from matplotlib import pyplot as plt


dateien = ['./2450ATT0.csv','./2450ATT0-1.csv','./2450ATT0-2.csv']
data_x = []
data_y = []
for datei in dateien: #do not call a variable "file" in python as this is protected
    x = np.genfromtxt(datei, usecols =(0), delimiter=';', unpack=True)
    x = x/1000000.
    y = np.genfromtxt(datei, usecols =(1), delimiter=';', unpack=True, dtype=float)
    data_x.append(x)
    data_y.append(y)


fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.18)
ax.set_xlim([2435,2465])
ax.set_xlim([-120,20])
ax.set_xlabel('Frequenz')
ax.set_ylabel('Leistung')

text = ax.text(0.98,0.98, dateien[0], ha="right", va="top")
line, = ax.plot(data_x[0],data_y[0], color="b")

ax_slider = fig.add_axes([0.1, 0.05, 0.8, 0.04])
slider = PageSlider(ax_slider, 'Page', len(dateien), activecolor="orange")

def update(val):
    i = int(slider.val)
    line.set_data(data_x[i],data_y[i])
    text.set_text(dateien[i])

slider.on_changed(update)

plt.show()


Edit:

For a simple animation, you would rather use matplotlib.animation.FuncAnimation and the code would look something along those lines

import numpy as np
from matplotlib import pyplot as plt

dateien = ['./2450ATT0.csv','./2450ATT0-1.csv','./2450ATT0-2.csv']
data_x = []
data_y = []
for datei in dateien: # do not call a variable "file" in python, this is a protected word
    x = np.genfromtxt(datei, usecols =(0), delimiter=';', unpack=True)
    x = x/1000000.
    y = np.genfromtxt(datei, usecols =(1), delimiter=';', unpack=True, dtype=float)
    data_x.append(x)
    data_y.append(y)


fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.18)
ax.set_xlim([2435,2465])
ax.set_xlim([-120,20])
ax.set_xlabel('Frequenz')
ax.set_ylabel('Leistung')

line, = ax.plot(data_x[0],data_y[0], color="b")

def update(i):
    line.set_data(data_x[i],data_y[i])

ani = matplotlib.animation.FuncAnimation(fig, update, 
            frames= len(dateien), interval = 200, blit = False, repeat= True)

plt.show()

这篇关于matplotlib仅以幻灯片形式显示一组10张图中的一个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 21:49