使用subplot和colorp与matplotlib将x轴与sharex对齐

时间:2019-02-01 05:38:40

标签: python matplotlib colorbar

我正在尝试使用pyplot创建一组具有共享x轴的子图。当图形简单且所有x轴对齐都很好时,这一切都很好。但是,当我包含包含色条的子图时,这会压缩该特定子图的宽度以包含色条,导致子图不再共享x轴。

我没有在网上搜索成功。我尝试了几种不同的方法,但是下面包括了最简单的示例。我在每个子图中绘制完全相同的数据,但用色条绘制一个。您会看到数据不再沿x轴对齐。

在此先感谢您的帮助!


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

Plot that I can't embed

3 个答案:

答案 0 :(得分:0)

创建子图时,您已经可以用颜色栏说明所需的内容。代替使用分隔线,使用gridspec_kw生成四个具有不同宽度的子图。然后,您可以删除第二个子图不需要的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')

结果如下:

result of the above code

作为删除不需要的子图实例的替代方法,您还可以首先显式生成gridspec并仅生成所需的子图。如果您有很多地块,这可能更合适:

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)

答案 1 :(得分:0)

这是一种骇人听闻的方法。

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

结果

enter image description here

答案 2 :(得分:0)

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,'.')

enter image description here