简体   繁体   English

删除pyplot中重叠的x轴标签

[英]Removing overlapping x-axis labels in pyplot

I'm new to python and attempting to chart some time series data.我是 python 的新手,并试图绘制一些时间序列数据。 I'm using pyplot to create 3 stacked line charts which have the same x-axis (dates), but a different scale for the y-axes.我正在使用 pyplot 创建 3 个堆叠折线图,它们具有相同的 x 轴(日期),但 y 轴的比例不同。 However, each y-axis, as well as the x-axis for the bottom chart, have overlapping labels.但是,每个 y 轴以及底部图表的 x 轴都有重叠的标签。 There are labels generated from 0 to 1, as well as axis labels from my data set.有从 0 到 1 生成的标签,以及来自我的数据集的轴标签。 How do I turn 'off' the auto-generated 0 to 1 labels on the y-axes and the bottom x-axis?如何关闭 y 轴和底部 x 轴上自动生成的 0 到 1 标签?

fig, ax = plt.subplots(3,1,sharex='all', squeeze=False, figsize=(12,8))

ax = fig.add_subplot(3,1,1)
plt.plot(df1['date'], df1['value'])

ax2 = fig.add_subplot(3,1,2)
plt.plot(df2['date'], df2['value'])

ax3 = fig.add_subplot(3,1,3)
plt.plot(df3['date'], df3['value'])
plt.show()

You can see the issue in the below picture.您可以在下图中看到问题。 Any help is greatly appreciated!任何帮助是极大的赞赏!

在此处输入图像描述

You have already created subplots with all the axes in the initial assignment您已经在初始分配中创建了包含所有轴的子图

fig, ax = plt.subplots(3,1,sharex='all', squeeze=False, figsize=(12,8))

therefore the following assignements of因此以下任务

ax = fig.add_subplot(3,1,1)
ax2 = fig.add_subplot(3,1,2)
ax3 = fig.add_subplot(3,1,3)

are not only unnecessary, but they seem to overlap the already created subplots (if you change it to add_subplot(2,1,1) you will notice it just starts dividing figure again and overlaying axes on top of each other).不仅没有必要,而且它们似乎与已经创建的子图重叠(如果将其更改为 add_subplot(2,1,1) 您会注意到它只是开始再次划分图形并将轴相互叠加)。

What you want to do, is access the axes created in plt.subplots() call:您想要做的是访问在 plt.subplots() 调用中创建的轴:

fig, ax = plt.subplots(3,1,sharex='all', squeeze=False, figsize=(12,8))

ax[0].plot(df1['date'], df1['value'])

ax[1].plot(df2['date'], df2['value'])

ax[2].plot(df3['date'], df3['value'])
plt.show()

Simulated Output:模拟 Output:

Data from seaborn tips dataset来自 seaborn 提示数据集的数据

在此处输入图像描述

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

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