简体   繁体   English

使用子图和带有 matplotlib 的颜色条将 x 轴与 sharex 对齐

[英]Aligning x-axis with sharex using subplots and colorbar with matplotlib

I'm trying to create a set of subplots with a shared x axis using pyplot.我正在尝试使用 pyplot 创建一组共享 x 轴的子图。 This is all fine and dandy when the graphs are simple and all the x-axes align fine.当图形很简单并且所有 x 轴都对齐时,这一切都很好。 However when I include a subplot that includes a colorbar, this compresses the width of that particular subplot to include the colorbar, resulting in the subplots no longer sharing the x-axis.但是,当我包含一个包含颜色条的子图时,这会压缩该特定子图的宽度以包含颜色条,从而导致子图不再共享 x 轴。

I've searched the web with no success with this.我在网上搜索过,但没有成功。 I've tried several different methods, but the simplest example I include below.我尝试了几种不同的方法,但我在下面包含了最简单的示例。 I plot the exact same data in each subplot, but plot one with a colorbar.我在每个子图中绘制完全相同的数据,但用颜色条绘制一个。 You can see the data no longer align along the x-axis.您可以看到数据不再沿 x 轴对齐。

Thanks in advance for your help!在此先感谢您的帮助!


import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import pandas as pd

x = np.linspace(0, 10, num=100)
y = x ** 2 + 10 * np.random.randn(100)


f, (ax1, ax2) = plt.subplots(2,1,sharex=True,figsize=(8,12))

im1 = ax1.scatter(x, y, c=y, cmap='magma')
divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size="5%", pad=.05)

plt.colorbar(im1, cax=cax)

im2 = ax2.plot(x, y,'.')

plt.show()

我无法嵌入的情节

This is one hacky way to do it.这是一种hacky的方式来做到这一点。

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import pandas as pd

x = np.linspace(0, 10, num=100)
y = x ** 2 + 10 * np.random.randn(100)


f, (ax1, ax2) = plt.subplots(2,1,sharex=True,figsize=(8,12))

im1 = ax1.scatter(x, y, c=y, cmap='magma')
divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size="5%", pad=.05)

plt.colorbar(im1, cax=cax)

im2 = ax2.plot(x, y,'.')
divider2 = make_axes_locatable(ax2)
cax2 = divider2.append_axes("right", size="5%", pad=.05)
cax2.remove()
plt.show()

results in结果是

在此处输入图片说明

Suggest using constrained_layout=True : https://matplotlib.org/stable/tutorials/intermediate/constrainedlayout_guide.html建议使用constrained_layout=Truehttps : //matplotlib.org/stable/tutorials/intermediate/constrainedlayout_guide.html

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, num=100)
y = x ** 2 + 10 * np.random.randn(100)

f, (ax1, ax2) = plt.subplots(2,1,sharex=True,figsize=(8,12),
        constrained_layout=True)
im1 = ax1.scatter(x, y, c=y, cmap='magma')
f.colorbar(im1, ax=ax1)
im2 = ax2.plot(x, y,'.')

在此处输入图片说明

You can account for the needed with of the colorbar already when you create the subplots.您可以在创建子图时考虑到颜色条的需要。 Instead of using the divider, generate four subplots with different widths using gridspec_kw .使用gridspec_kw生成四个不同宽度的子图,而不是使用gridspec_kw You can then delete the unneeded cax for the second subplot:然后,您可以删除第二cax图不需要的cax

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, num=100)
y = x ** 2 + 10 * np.random.randn(100)



##creating four subplots with unequally divided widths:
f, axes = plt.subplots(
    2,2, sharex='col', figsize=(8,12),
    gridspec_kw = {'width_ratios' : (10,1)},
)
ax1,ax2 = axes[:,0]

##remove unneeded Axes instance:
axes[1,1].remove()

im1 = ax1.scatter(x, y, c=y, cmap='magma')
plt.colorbar(im1, cax=axes[0,1])

im2 = ax2.plot(x, y,'.')

f.savefig('sharex_colorbar.png')

The result looks like this:结果如下所示:

上面代码的结果

As an alternative to deleting the unneded subplot instances, you can also first generate the gridspec explicitly and generate only the needed subplots.作为删除 unneded 子图实例的替代方法,您还可以首先显式生成 gridspec 并仅生成所需的子图。 This might be more suitable if you have many plots:如果您有很多情节,这可能更合适:

from matplotlib.gridspec import GridSpec
gs = GridSpec(nrows=2, ncols=2, width_ratios = (10,1))
f = plt.figure(figsize=(8,12))

ax1 = f.add_subplot(gs[0,0])
ax2 = f.add_subplot(gs[1,0],sharex=ax1)
cax = f.add_subplot(gs[0,1])

im1 = ax1.scatter(x, y, c=y, cmap='magma')
plt.colorbar(im1, cax=cax)

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

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