我知道这个话题已经在几个 matplotlib 博客中解决了,但我仍然找不到解决方案。我想创建一个这样的情节:
(来自@ImportanceOfBeingErnest 的回答的情节)
所以这是两个子图,它们与我定义的 y 限制共享相同的 y 轴。x 轴的单位应该与 y 轴的单位相同,这意味着如果我要画一个圆,它确实是一个圆。
现在我还想指定 x-limits 并喜欢 subplot 大小来调整到这个限制,但我不能让它工作。一般的问题似乎是 matplotlib 总是保持不同子图的 fig-size 。
这是一个最小的工作示例:
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax1=fig.add_subplot(1,2,1,aspect='equal')
ax2=fig.add_subplot(1,2,2,aspect='equal',sharey=ax1)
def create_data(xmin,xmax):
delta = 0.025
----
x = np.arange(xmin, xmax, delta)
y = np.arange(-3,3,delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1 - Z2)
----
nr, nc = Z.shape
----
# put NaNs in one corner:
Z[-nr//6:, -nc//6:] = np.nan
# contourf will convert these to masked
----
----
Z = np.ma.array(Z)
# mask another corner:
Z[:nr//6, :nc//6] = np.ma.masked
----
# mask a circle in the middle:
interior = np.sqrt((X**2) + (Y**2)) < 0.5
Z[interior] = np.ma.masked
return X,Y,Z
X,Y,Z=create_data(-2,4)
ax1.contourf(X,Y,Z)
ax1.set_ylim(-1,1)
ax1.set_xlim(-2,4)
X,Y,Z=create_data(-1,0)
ax2.contourf(X,Y,Z)
ax2.set_ylim(-1,1)
ax2.set_xlim(-1,0)
plt.show()
在此示例中,y 轴是共享的,但 x 限制未正确应用:
此外,如何在与 y 轴对齐的子图右侧添加颜色条?
fig.colorbar(CS, ax=ax,shrink=xx)
似乎工作,但需要手动编辑收缩参数。
由于两个图的 x 限制范围之间的比率为 1/6,因此如果它们应保持相同的高度,这些图的大小也需要偏离 6 倍。
(请注意,早期版本的 matplotlib 显然可能存在错误,这使得以下代码无法按预期工作;但是,它在 matplotlib 2.2 中运行良好)
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1,ax2) = plt.subplots(ncols=2, sharey=True,
subplot_kw=dict(aspect='equal'),
gridspec_kw=dict(width_ratios=[6,1]))
def create_data(xmin,xmax):
delta = 0.025
x = np.arange(xmin, xmax, delta)
y = np.arange(-3,3,delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1 - Z2)
nr, nc = Z.shape
# put NaNs in one corner:
Z[-nr//6:, -nc//6:] = np.nan
# contourf will convert these to masked
Z = np.ma.array(Z)
# mask another corner:
Z[:nr//6, :nc//6] = np.ma.masked
# mask a circle in the middle:
interior = np.sqrt((X**2) + (Y**2)) < 0.5
Z[interior] = np.ma.masked
return X,Y,Z
X,Y,Z=create_data(-2,4)
ax1.contourf(X,Y,Z)
ax1.set_ylim(-1,1)
ax1.set_xlim(-2,4)
X,Y,Z=create_data(-1,0)
ax2.contourf(X,Y,Z)
ax2.set_ylim(-1,1)
ax2.set_xlim(-1,0)
plt.show()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句