简体   繁体   English

如何在matplotlib中格式化多个图的x轴

[英]How to format x-axis for multiple plots in matplotlib

I'm currently generating three different figures and I'm having trouble trying to set the format for the x-axis for all three plots. 我目前正在生成三个不同的数字,我在设置所有三个图的x轴格式时遇到了麻烦。 This is what I have currently. 这就是我目前所拥有的。

    fig, ax = plt.subplots()

    plt.figure(1)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates1, y1)
    plt.show()

    plt.figure(2)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates2, y2)
    plt.show()

    plt.figure(3)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates3, y3)
    plt.show()

The first figure is formatted as desired but the second and third figure can't seem to detect the x-axis formatting specified. 第一个数字按需要格式化,但第二个和第三个数字似乎无法检测指定的x轴格式。 What is the correct way of doing this and is there a way to set the formatting for all three graphs at once? 这样做的正确方法是什么,有没有办法一次设置所有三个图形的格式?

You can use plt.close() to discard plot instances. 您可以使用plt.close()来丢弃绘图实例。 Or assign each to it's own variable. 或者将每个分配给它自己的变量。

    plt.figure(1)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates1, y1)
    plt.show()
    plt.close()


    plt.figure(2)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates2, y2)
    plt.show()
    plt.close()

    plt.figure(3)
    formatter = DateFormatter('%m/%d/%y')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30)
    plt.plot_date(dates3, y3)
    plt.show()
    plt.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM