【python】为什么matplotlib的ax.set_xticklabel()放在类的__init__()里就没用?

因为要画很多图就写了个画图类,但是初始化的时候加上ax.set_xticklabels()就会没用。

class DrawCharts:
    def __init__(self, title='', xlabel='', ylabel='', xticks=None, yticks=None, xticklabels=None, yticklabels=None, xscale='linear', yscale='linear', autofmt_x=True):
        self.title = title
        self.xlabel = xlabel
        self.ylabel = ylabel
        self.xticks = xticks
        self.yticks = yticks
        self.xticklabels = xticklabels
        self.yticklabels = yticklabels
        self.xscale = xscale
        self.yscale = yscale
        self.autofmt_x = autofmt_x
        # 解决中文显示问题
        self.font = {'family': 'SimHei',  # 字体:黑体
                     'size': '16'}   # 字号:16
        plt.rc('font', **self.font)  # 设置字体的更多属性
        plt.rc('axes', unicode_minus=False)  # 解决坐标轴负数的负号显示问题
        self.fig, self.ax = plt.subplots()

        self.ax.set_title(self.title)
        self.ax.set_xlabel(self.xlabel)
        self.ax.set_ylabel(self.ylabel)
        if self.xticks is not None:
            self.ax.set_xticks(self.xticks)
        if self.yticks is not None:
            self.ax.set_yticks(self.yticks)
        if self.xticklabels is not None:
            self.ax.set_xticklabels(self.xticklabels)
        if self.yticklabels is not None:
            self.ax.set_yticklabels(self.yticklabels)
        self.ax.set_xscale(self.xscale)  # 坐标轴:线性:'linear',指数:'symlog'
        self.ax.set_yscale(self.yscale)
        if self.autofmt_x == True:
            self.fig.autofmt_xdate()

    def show_figs(self):
        plt.show()

    def draw_plot(self, xdata, ydata, color='dodgerblue', label=''):
        self.ax.plot(xdata, ydata, color=color, label=label)

if __name__ == "__main__":
    x = [1, 2, 3]
    y = [1, 5, 7]
    chart = DrawCharts('图形', 'x标签', 'y标签',xticks=[1, 2, 3], xticklabels=['a', 'b', 'c'])
    chart.draw_plot(x, y)
    chart.show_figs()

这样执行出来就完全没有自定义标签。
xticklabels无效

但是这样的话,就能显示了。

if __name__ == "__main__":
    x = [1, 2, 3]
    y = [1, 5, 7]
    chart = DrawCharts('图形', 'x标签', 'y标签')
    chart.ax.set_xticks([1, 2, 3])
    chart.ax.set_xticklabels(['a', 'b', 'c'])
    chart.draw_plot(x, y)
    chart.show_figs()

xticklabels显示

想问下大佬们为什么。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!