【问题标题】:How to get rid of extra white space on subplots with shared axes?如何摆脱共享轴的子图上的额外空白?
【发布时间】:2016-09-08 01:14:33
【问题描述】:

我正在使用 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 轴。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    自动缩放倾向于为数据添加一个缓冲区,以便所有数据点都很容易看到,并且不会被轴截断。

    变化:

    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())
    

    获得:

    【讨论】:

    • 通常我喜欢自动缩放“帮助我”,但是当与图像(或看起来像图像的东西)结合时,额外的空白很烦人。谢谢,我整天都在为此奋斗。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2017-04-23
    • 2012-11-09
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多