使用subplot和colorp与matplotlib将x轴与sharex对齐 [英] Aligning x-axis with sharex using subplots and colorbar with matplotlib
问题描述
我正在尝试使用pyplot创建一组具有共享x轴的子图.当图形简单且所有x轴对齐都很好时,这一切都很好.但是,当我包含包含色条的子图时,这会压缩该特定子图的宽度以包含色条,导致子图不再共享x轴.
I'm trying to create a set of subplots with a shared x axis using pyplot. This is all fine and dandy when the graphs are simple and all the x-axes align fine. 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.
提前感谢您的帮助!
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()
推荐答案
这是一种简单的方法.
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()
结果
这篇关于使用subplot和colorp与matplotlib将x轴与sharex对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!