我正在使用 python 3.5.1 和 matplotlib 1.5.1 创建一个图,该图有两个带有共享 Y 轴的子图(并排)。示例输出图像如下所示:
请注意每组轴顶部和底部的额外空白。尽我所能,我似乎无法摆脱它。该图的总体目标是在左侧绘制一个瀑布型图,并与右侧的图共享 Y 轴。
这里有一些示例代码来重现上面的图像。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline
# create some X values
periods = np.linspace(1/1440, 1, 1000)
# create some Y values (will be datetimes, not necessarily evenly spaced
# like they are in this example)
day_ints = np.linspace(1, 100, 100)
days = pd.to_timedelta(day_ints, 'D') + pd.to_datetime('2016-01-01')
# create some fake data for the number of points
points = np.random.random(len(day_ints))
# create some fake data for the color mesh
Sxx = np.random.random((len(days), len(periods)))
# Create the plots
fig = plt.figure(figsize=(8, 6))
# create first plot
ax1 = plt.subplot2grid((1,5), (0,0), colspan=4)
im = ax1.pcolormesh(periods, days, Sxx, cmap='viridis', vmin=0, vmax=1)
ax1.invert_yaxis()
ax1.autoscale(enable=True, axis='Y', tight=True)
# create second plot and use the same y axis as the first one
ax2 = plt.subplot2grid((1,5), (0,4), sharey=ax1)
ax2.scatter(points, days)
ax2.autoscale(enable=True, axis='Y', tight=True)
# Hide the Y axis scale on the second plot
plt.setp(ax2.get_yticklabels(), visible=False)
#ax1.set_adjustable('box-forced')
#ax2.set_adjustable('box-forced')
fig.colorbar(im, ax=ax1)
正如您在注释掉的代码中看到的那样,我尝试了多种方法,正如 https://github.com/matplotlib/matplotlib/issues/1789/ 等帖子所建议的那样。和 Matplotlib: set axis tight only to x or y axis .
一旦我删除第二个 subplot2grid 调用的 sharey=ax1
部分,问题就会消失,但我也没有通用的 Y 轴。
最佳答案
自动缩放倾向于向数据添加缓冲区,以便所有数据点都易于可见,并且不会被轴部分切断。
更改:
ax1.autoscale(enable=True, axis='Y', tight=True)
至:
ax1.set_ylim(days.min(),days.max())
和
ax2.autoscale(enable=True, axis='Y', tight=True)
至:
ax2.set_ylim(days.min(),days.max())
获取:
关于python - 如何消除具有共享轴的子图上的额外空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381162/