python - matplotlib 中具有相同数量 xticklabels 的六个子图

标签 python matplotlib axis label subplot

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

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

graph4.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.py 中的方法 clear_plot() 来重置所有子图。然后将文件名列表传递给 graph4.py 中的方法 plot()plot() 方法打开每个文件并在不同的子图中绘制每个数据集。所以在我双击一个条目后,它看起来像:

enter image description here

如您所见,每个子图都有不同数量的 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 Axis 是否是一个真正的好主意,因为每个子图中的 x 值可能不同(例如:在第一个子图中,x 值范围从上午 8:00 - 上午 11:00,在第二个子图中,x 值的范围是晚上 7:00 - 晚上 9:00)。

如果我去掉 sharex = True,我会得到以下输出:

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

如您所见,输出现在看起来更好了。但是现在,x Axis 上的标签没有更新。我假设那是因为最后的 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()add_subplot() 相同的问题。

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

最佳答案

我强烈建议您使用 pyplot.subplots()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'

关于python - matplotlib 中具有相同数量 xticklabels 的六个子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17379351/

相关文章:

python - 获取每个训练实例的损失值 - Keras

具有多个标题的python matplotlib绘图表

python - Python 中的 MySQL 查询速度较慢,但​​其他地方速度较快

python - 使用 python 计算 AVRO 文件中的行数

python - 从各个方向随机生成玩家周围的敌人

python - 具有稀疏矩阵的matshow

python - Matplotlib 饼图作为散点图

python - 为流线型 line_chart 添加标签 x Axis 和 y Axis

javascript - 使用 Highcharts.js 在 x Axis 上显示日期

java - 如何从 Axis 1.4 stub 打印 XML 请求和响应