python - 在 gridspec 项内具有共享轴的多个子图
问题描述
我想要一个有 2 列和 1 行的网格。第一列将包含不同国家/地区的地图,第二列应为垂直堆叠的地图中的每个国家/地区提供一个图。
这些图应该共享 x 轴,我想plt.subplots
与sharex=True
.
但是,在我看到的示例中(例如这个),他们首先创建网格,然后一次添加一个子图。这样我猜我就不能使用共享轴了。有没有办法结合网格来做到这一点?
期望的输出:
我尝试的是为网格定义与在我的图右侧分别绘制的国家数量一样多的行,而没有找到使用sharex=True
.
这是一个简化的示例(从https://towardsdatascience.com/plot-organization-in-matplotlib-your-one-stop-guide-if-you-are-reading-this-it-is-probably-f79c2dcbc801修改) :
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
time = np.linspace(0, 10, 1000)
height = np.sin(time)
weight = time*0.3 + 2
score = time**2 + height
distribution = np.random.normal(0, 1, len(time))
fig = plt.figure(figsize=(10, 5))
gs = gridspec.GridSpec(nrows=2, ncols=2)
ax0 = fig.add_subplot(gs[:, 0])
ax0.plot(time, height)
ax1 = fig.add_subplot(gs[0, 1])
ax1.plot(time, weight)
ax2 = fig.add_subplot(gs[1, 1])
plt.show()
解决方案
好的,抱歉,我在这里找到了解决方案。
诀窍是设置sharex
等于已创建的 x 轴之一,然后显式隐藏除下图以外的所有 x 刻度(在我的情况下)。
这是修改后的代码:
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
time = np.linspace(0, 10, 1000)
height = np.sin(time)
weight = time*0.3 + 2
score = time**2 + height
distribution = np.random.normal(0, 1, len(time))
fig = plt.figure(figsize=(10, 5))
gs = gridspec.GridSpec(nrows=2, ncols=2)
ax0 = fig.add_subplot(gs[:, 0])
ax0.plot(time, height)
ax1 = fig.add_subplot(gs[1, 1])
ax1.plot(time, weight)
ax2 = fig.add_subplot(gs[0, 1], sharex=ax1)
plt.setp(ax2.get_xticklabels(), visible=False)
plt.show()
推荐阅读
- react-native - 如何在 react-native 中创建 pdf 文件?
- amazon-ec2 - 为什么 AWS.EC2MetadataCredentials 赋予错误的角色?
- java - 如何在下载 JAR 文件时禁用“此文件可能会损害您的计算机”chrome 浏览器消息?
- c# - 为什么我的导出到excel功能会导出整个页面?
- arrays - 获取数组值红宝石
- android-collapsingtoolbarlayout - 限制嵌套滚动视图在不需要滚动内容时停止滚动
- android - 使用 Livedata 时如何为 RecyclerView 使用 Filter SearchView?
- javascript - 如何在 openlayers 中添加自定义比例线?
- python-3.x - 如何使用 py2neo.ogm (v3) 为不同类型的节点创建双向关系?
- c# - 删除“csproj”中没有副作用的“obj”文件夹