3

我真的在 matplotlib 上苦苦挣扎,尤其是轴设置。我的目标是在一个图中设置 6 个子图,它们都显示不同的数据集,但具有相同数量的刻度标签。

我的源代码的相关部分如下所示:

图4.py:

# Import Matolotlib Modules #
import matplotlib as mpl
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
from matplotlib import ticker
import matplotlib.pyplot as plt

mpl.rcParams['font.sans-serif']='Arial' #set font to arial 

# Import GTK Modules #

import gtk

#Import System Modules #
import sys

# Import Numpy Modules #
from numpy import genfromtxt
import numpy

# Import Own Modules #
import mysubplot as mysp

class graph4():
    weekdays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag']

    def __init__(self, graphview):
        #create new Figure
        self.figure = Figure(figsize=(100,100), dpi=75)

        #create six subplots within self.figure
        self.subplot = []
        for j in range(6):
            self.subplot.append(self.figure.add_subplot(321 + j))


        self.__conf_subplots__() #configure title, xlabel, ylabel and grid of all subplots  


        #to make it look better    
        self.figure.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.96, wspace=0.2, hspace=0.6)    

        #Matplotlib <-> GTK
        self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea 
        self.canvas.set_flags(gtk.HAS_FOCUS|gtk.CAN_FOCUS)
        self.canvas.grab_focus()
        self.canvas.show()
        graphview.pack_start(self.canvas, True, True)


        #add labels and grid to all subplots  
        def __conf_subplots__(self):
            index = 0
            for i in self.subplot: 
                mysp.conf_subplot(i, 'Zeit', 'Menge', graph4.weekdays[index], True)
                i.plot([], [], 'bo') #empty plot
                index +=1


        def plot(self, filename_list):
            index = 0
            for filename in filename_list:
                data = genfromtxt(filename, delimiter=',') #load data from filename
                if data.size != 0: #only if file isn't empty
                    if index <= len(self.subplot): #plot every file on a different subplot
                        mysp.plot(self.subplot[index],data[0:, 1], data[0:, 0])
                        index +=1


            self.canvas.draw()


            def clear_plot(self):
                #clear axis of all subplots 
                for i in self.subplot:
                    i.cla()

                self.__conf_subplots__() 

mysubplot.py:(帮助模块)

# Import Matplotlib Modules
from matplotlib.axes import Subplot 
import matplotlib.dates as md
import matplotlib.pyplot as plt

# Import Own Modules #
import mytime as myt

# Import Numpy Modules #
import numpy as np

def conf_subplot(subplot, xlabel, ylabel, title, grid):
    if(xlabel != None):
        subplot.set_xlabel(xlabel) 
    if(ylabel != None):
        subplot.set_ylabel(ylabel) 
    if(title != None):
        subplot.set_title(title) 
    subplot.grid(grid)

    #rotate xaxis labels 
    plt.setp(subplot.get_xticklabels(), rotation=30, fontsize=12)

    #display date on xaxis
    subplot.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))      
    subplot.xaxis_date()


def plot(subplot, x, y):
    subplot.plot(x, y, 'bo') 

我认为解释问题的最好方法是使用屏幕截图。启动应用程序后,一切看起来都很好:

http://i.imgur.com/SqwaPyG.png

如果我双击左侧的“周”条目,则会调用graph4.pyclear_plot()中的方法来重置所有子图。然后将文件名列表传递给graph4.py中的方法。该方法打开每个文件并将每个数据集绘制在不同的子图上。所以在我双击一个条目后,它看起来像:plot()plot()

在此处输入图像描述

如您所见,每个子图都有不同数量的 xtick 标签,这对我来说看起来很丑陋。因此,我正在寻找一种解决方案来改善这一点。我的第一种方法是使用 手动设置刻度标签xaxis.set_ticklabels(),以便每个子图具有相同数量的刻度标签。然而,听起来很奇怪,这只适用于某些数据集,我真的不知道为什么。在某些数据集上,一切正常,而在其他数据集上,matplotlib 基本上是在做它想做的事情,并显示我没有指定的 xaxis 标签。我也试过FixedLocator()了,但我得到了同样的结果。在它正在工作的一些数据集和其他数据集上,matplotlib 使用不同数量的 xtick 标签。

我究竟做错了什么?

编辑:

正如@sgpc 建议的那样,我尝试使用pyplot。我的源代码现在看起来像这样:

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
import matplotlib.dates as md

mpl.rcParams['font.sans-serif']='Arial' #set font to arial 

import gtk
import sys

# Import Numpy Modules #
from numpy import genfromtxt
import numpy

# Import Own Modules #
import mysubplot as mysp

class graph2():
    weekdays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag']

    def __init__(self, graphview):
        self.figure, temp = plt.subplots(ncols=2, nrows=3, sharex = True)

        #2d array -> list
        self.axes = [ y for x in temp for y in x]

        #axis: date
        for i in self.axes:
            i.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))
            i.xaxis_date()  

        #make space and rotate xtick labels
        self.figure.autofmt_xdate() 

        #Matplotlib <-> GTK
        self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea 
        self.canvas.set_flags(gtk.HAS_FOCUS|gtk.CAN_FOCUS)
        self.canvas.grab_focus()
        self.canvas.show()
        graphview.pack_start(self.canvas, True, True)

    def plot(self, filename_list):
        index = 0
        for filename in filename_list:
            data = genfromtxt(filename, delimiter=',') #get dataset
            if data.size != 0: #only if file isn't empty
                if index < len(self.axes): #print each dataset on a different subplot 
                    self.axes[index].plot(data[0:, 1], data[0:, 0], 'bo')
                    index +=1

        self.canvas.draw()

    #not yet implemented
    def clear_plot(self):
        pass

如果我绘制一些数据集,我会得到以下输出:http: //i.imgur.com/3ngYTNr.png(对不起,我仍然没有足够的声誉来嵌入图片)

此外,我不确定共享 x 轴是否真的是一个好主意,因为每个子图中的 x 值可能不同(例如:在第一个子图中,x 值的范围从上午 8:00 开始- 上午 11:00,在第二个子图中,x 值的范围是晚上 7:00 - 晚上 9:00)。

如果我摆脱sharex = True,我会得到以下输出:

http://i.imgur.com/rxHeSyJ.png(对不起,我还没有足够的声望嵌入图片)

如您所见,输出现在看起来更好了。但是现在,x 轴上的标签没有更新。我认为这是因为最后一个 suplots 是空的。

我的下一个尝试是为每个子图使用一个轴。因此,我进行了以下更改:

for i in self.axes:
    plt.setp(i.get_xticklabels(), visible=True, rotation = 30) #<-- I added this line...
    i.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))
    i.xaxis_date() 

#self.figure.autofmt_xdate() #<--changed this line
self.figure.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.96, wspace=0.2, hspace=0.6) #<-- and added this line

现在我得到以下输出:

i.imgur.com/TmA1goE.png(对不起,我还没有足够的声望嵌入图片)

因此,通过这次尝试,我基本上正在努力解决与Figure()and相同的问题add_subplot()

我真的不知道,我还能尝试什么让它工作......

4

1 回答 1

0

我强烈建议您使用pyplot.subplots()with sharex=True

fig, axes = subplots(ncols=2, nrows=3, sharex= True)

然后您使用以下命令访问每个轴:

ax = axes[i,j]

你可以策划做:

ax.plot(...)

要控制每个刻度的数量,AxesSubplot您可以使用:

ax.locator_params(axis='x', nbins=6)

OBS:axis可以'x''y''both'

于 2013-06-29T12:06:04.130 回答