0

我正在尝试编辑一个我发现将 mataplot 嵌入 wx 框架的示例。

当我执行代码时,它可以工作: - 从 CSV 中读取包含日期、每行频率的数据(例如“2009-01-10, 100”) - 在 wx 框架中正确绘制图表。

但是,我试图弄清楚如何使 x 轴显示来自 csv 数据的日期而不是 1、2、4、5、6 .. 我能够在我使用的另一个 python 程序中正确地做到这一点:

plt.xticks(range(len(dates)), (dates), rotation=45)

但无法弄清楚如何在这里做类似的事情..

#!/usr/bin/env python
"""
An example of how to use wx or wxagg in an application with the new
toolbar - comment out the setA_toolbar line for no toolbar
"""

# Used to guarantee to use at least Wx2.8
import wxversion
wxversion.ensureMinimal('2.8')
import csv
from numpy import arange, sin, pi

import matplotlib

# uncomment the following to use wx rather than wxagg
#matplotlib.use('WX')
#from matplotlib.backends.backend_wx import FigureCanvasWx as FigureCanvas

# comment out the following to use wx rather than wxagg
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

from matplotlib.backends.backend_wx import NavigationToolbar2Wx

from matplotlib.figure import Figure

import wx

class CanvasFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self,None,-1,
                         'CanvasFrame',size=(550,350))

        self.SetBackgroundColour(wx.NamedColor("WHITE"))

        self.figure = Figure()

        with open('c:\\charts.csv', 'rb') as n:
            reader = csv.reader(n)
            dates = []
            freq = []
            for row in reader:
                values = row[0].split(',')
                dates.append(values[0])
                freq.append(values[1])

        self.axes = self.figure.add_subplot(111)



        false_x = [x for x in range(len(dates))]
        self.axes.plot(false_x,freq, 'o-')
        ##self.axes.plot(t,s)
       # self.axes.plot.xticks(range(len(dates)), (dates), rotation=45)
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()  # comment this out for no toolbar


    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            # Mac platform (OSX 10.3, MacPython) does not seem to cope with
            # having a toolbar in a sizer. This work-around gets the buttons
            # back, but at the expense of having the toolbar at the top
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()


    def OnPaint(self, event):
        self.canvas.draw()

class App(wx.App):

    def OnInit(self):
        'Create the main window and insert the custom frame'
        frame = CanvasFrame()
        frame.Show(True)

        return True

app = App(0)
app.MainLoop()

在此先感谢您的帮助!

4

1 回答 1

1

这是 xticks() 的代码:

def xticks(*args, **kwargs):
    ax = gca()

    if len(args)==0:
        locs = ax.get_xticks()
        labels = ax.get_xticklabels()
    elif len(args)==1:
        locs = ax.set_xticks(args[0])
        labels = ax.get_xticklabels()
    elif len(args)==2:
        locs = ax.set_xticks(args[0])
        labels = ax.set_xticklabels(args[1], **kwargs)
    else: raise TypeError('Illegal number of arguments to xticks')
    if len(kwargs):
        for l in labels:
            l.update(kwargs)

    draw_if_interactive()
    return locs, silent_list('Text xticklabel', labels)

你这样称呼它:

plt.xticks(range(len(dates)), (dates), rotation=45)

因此您可以使用 xticks() 中处理len(args)==2. 在代码中调用后添加以下两行self.axes.plot(...)

self.axes.set_xticks(range(len(dates)))
self.axes.set_xticklabels(dates, rotation=45)
于 2012-04-21T22:57:10.347 回答