简体   繁体   English

matplotlib中的轴尺寸如何调整?

[英]How to adjust the axis size in matplotlib?

My goal is to create a hierarchical x-axis with the dates.我的目标是创建一个带有日期的分层 x 轴。 To do this, I am following the steps of this answer .为此,我正在按照此答案的步骤进行操作。 I have the day on the first x-axis:我在第一个 x 轴上有一天:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker

date = ['2021-01-29', '2021-01-30', '2021-01-31',
        '2021-02-01', '2021-02-02', '2021-01-03', '2021-01-04']
day = ['29', '30', '31', '01', '02', '03', '04']
data = [5, 4, 3, 9, 7, 8, 2]

fig = plt.figure(num="TEST")
ax1 = fig.add_subplot(1, 1, 1)

ax1.plot(date, data)

ax1.set_xticks(date)
ax1.set_xticklabels(day)
ax1.margins(x=0)

plt.show()

And with the following code block, I generate the month on the second x-axis:使用以下代码块,我在第二个 x 轴上生成月份:

ax2 = ax1.twiny()

ax2.spines['bottom'].set_position(('axes', -0.08))
ax2.tick_params('both', direction='in', which='major')
ax2.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_label_position('bottom')

ax2.set_xticks([0, 2.5, 6])
ax2.xaxis.set_major_formatter(ticker.NullFormatter())
ax2.xaxis.set_minor_locator(ticker.FixedLocator([1, 4]))
ax2.xaxis.set_minor_formatter(ticker.FixedFormatter(['JAN', 'FEB']))

This works perfectly on a line plot:这在 plot 线上完美运行:

在此处输入图像描述

However, when I change the chart type to bar ax1.bar(date, data) , the beginning and end ticks of both axis don't match:但是,当我将图表类型更改为 bar ax1.bar(date, data)时,两个轴的开始和结束刻度不匹配:

在此处输入图像描述

Is there a way for both axis to start and end at the same point?有没有办法让两个轴在同一点开始和结束? Either extending the first axis all the way (regardless overlapping) or adjusting the second axis to match the first axis.一直延伸第一个轴(无论重叠)或调整第二个轴以匹配第一个轴。

To get both x-axis nicely aligned, it is important that they have the same datalimits ( ax2.set_xlim(ax1.get_xlim()) ).为了使两个 x 轴很好地对齐,它们具有相同的数据限制 ( ax2.set_xlim(ax1.get_xlim()) ) 很重要。 Then, ax2.set_xticks([0, 2.5, 6]) will have the ticks at the center of the first and last bar, and inbetween the third and fourth.然后, ax2.set_xticks([0, 2.5, 6])将在第一个和最后一个柱的中心以及第三个和第四个之间有刻度。

You can use ax2.spines['bottom'].set_bounds([0, 6]) to stop the x-axis at those positions.您可以使用ax2.spines['bottom'].set_bounds([0, 6])在这些位置停止 x 轴。

If you also want to hide the tick marks of ax1 , the standard way is to set their length to zero: ax1.tick_params(axis='x', length=0) .如果您还想隐藏ax1的刻度线,标准方法是将它们的长度设置为零: ax1.tick_params(axis='x', length=0)

If desired, you can also hide the top and right spines.如果需要,您还可以隐藏顶部和右侧的脊椎。 You'll need to do that for both axes.您需要对两个轴都这样做。

from matplotlib import pyplot as plt
import matplotlib.ticker as ticker

date = ['2021-01-29', '2021-01-30', '2021-01-31',
        '2021-02-01', '2021-02-02', '2021-01-03', '2021-01-04']
day = ['29', '30', '31', '01', '02', '03', '04']
data = [5, 4, 3, 9, 7, 8, 2]

fig, ax1 = plt.subplots(num="TEST")

ax1.bar(date, data)

ax1.set_xticks(np.arange(len(date)))
ax1.set_xticklabels(day)
ax1.margins(x=0)
ax1.tick_params(axis='x', length=0)  # hide tick marks

ax2 = ax1.twiny()

ax2.spines['bottom'].set_position(('axes', -0.08))
ax2.tick_params(axis='x', direction='in', which='major')
ax2.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_label_position('bottom')

ax2.set_xlim(ax1.get_xlim()) # same datalimits
ax2.set_xticks([0, 2.5, 6])
ax2.spines['bottom'].set_bounds([0, 6])
ax2.xaxis.set_major_formatter(ticker.NullFormatter())
ax2.xaxis.set_minor_locator(ticker.FixedLocator([1, 4]))
ax2.xaxis.set_minor_formatter(ticker.FixedFormatter(['JAN', 'FEB']))

for ax in (ax1, ax2):
    for spine in ['top', 'right']:
        ax.spines[spine].set_visible(False)

plt.tight_layout()
plt.show()

Instead of shorten, set_bounds() can also extend a bit.除了缩短, set_bounds()还可以扩展一点。 For example:例如:

ax2.set_xticks([-0.5, 2.5, 6.5])
ax2.spines['bottom'].set_bounds([-0.5, 6.5])

调整第二个 x 轴的长度

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

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