我想使用马赛克创建一个包含 2 个子图的图形,并使用 Matplotlib 在极坐标和笛卡尔坐标中显示相同的信号。
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0, 30, 0.1)
s = np.sin(2 * np.pi * 1 * t)
fig = plt.figure(layout="constrained")
ax_dict = fig.subplot_mosaic(
[
["signal1"],
["signal2"],
]
)
p1 = ax_dict["signal1"].plot(s)
p2 = ax_dict["signal2"].plot(s)
plt.show()
所以我想在左侧显示笛卡尔坐标中的图形,在右侧显示极坐标中的图形。怎么可能?
提前谢谢您。
我非常感谢kho的答案。如果您欣赏我的回答,请首先考虑欣赏他们的回答。
我已经测试了简单的
subplot_mosaic
配置的答案。
我还没有测试过它是否适用于更复杂的配置,我不能保证我的答案适用于这些复杂的安排。
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 10*(2*np.pi), 1001)
f = np.sin(t)*np.cos(t/40)
def update_projection(axd, label, projection='polar', fig=None):
# adapted from https://stackoverflow.com/a/75485793/2749397
# by https://stackoverflow.com/users/15330539/kho
if fig is None: fig = plt.gcf()
rows, cols, start, stop = axd[label].get_subplotspec().get_geometry()
axd[label].remove()
axd[label] = fig.add_subplot(rows, cols, start+1, projection=projection)
fig = plt.figure(layout="constrained", figsize=(10, 7))
ax_dict = fig.subplot_mosaic([["a", "a", "b"],
['c', 'd', 'd']])
update_projection(ax_dict, 'b', 'polar', fig)
update_projection(ax_dict, 'c', 'polar', fig)
ax_dict['a'].plot(t, f); ax_dict['b'].plot(t, f);
ax_dict['c'].plot(t, f); ax_dict['d'].plot(t, f);
plt.savefig('cartesian_polar.png', dpi=200)