【发布时间】:2019-09-14 10:19:59
【问题描述】:
我正在构建一个图形,其主轴是散点图,缩放轴聚焦于主轴的特定区域,两者都有网格线。当我将缩放轴作为插图放置时,它会“覆盖”一些主轴数据。我希望能够通过缩放轴显示主轴数据(zorder=100),因此我将缩放轴设置为透明(alpha=0)。最后,我希望主轴网格线在与缩放轴 (zorder=10) 相遇时“截断”,但我想显示缩放轴网格线 (zorder=50)。这可能吗?以下是我的尝试:
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
import numpy as np
fig = plt.figure(figsize=(10,7.5))
gs = matplotlib.gridspec.GridSpec(1, 2, width_ratios=[20,1], height_ratios=[1])
ax = plt.subplot(111)
## data
xx = np.linspace(1,100,num=100) + 20 * np.random.normal(0,1,100)
yy = np.linspace(1,100,num=100) + 10 * np.random.normal(0,1,100)
## scatter
sc = ax.scatter(xx, yy, s=250, alpha=0.35, zorder=100)
ax.plot(np.linspace(-100,200,301), np.linspace(-100,200,301),)
ax.set_xlim((0, 100))
ax.set_ylim((0, 100))
ax.grid(linestyle="--", zorder=10)
## zoom
axins = zoomed_inset_axes(ax, 2, loc="upper left")
scins = axins.scatter(xx, yy, s=100, alpha=0.35, zorder=50, marker=".", c="red")
axins.plot(np.linspace(-100,200,301), np.linspace(-100,200,301), c="red")
axins.set_xlim((70, 90))
axins.set_ylim((70, 90))
mark_inset(ax, axins, loc1=1, loc2=4, fc="none", ec="0.5")
axins.grid(linestyle="--", zorder=50)
plt.show()
特别是,x=80 附近的蓝色数据点之一被截断。我可以设置axins.patch.set_alpha(0.0),但它不会删除主网格线。
【问题讨论】:
-
axins.patch.set_alpha(0.0)工作正常。您需要注意 zorder 按轴工作。所以假设你有两个轴,ax1使用 zorder=1,ax2使用 zorder=2。然后,ax2中的每个艺术家将在ax1中的任何艺术家之上。 -
@ImportanceOfBeingErnest:那么有没有办法同时显示缩放轴的网格线和主轴的数据?
-
当使用
axins.patch.set_alpha(0.0)looks like this 时,它会同时显示来自缩放轴的网格线和来自主轴的数据。 -
@ImportanceOfBeingErnest:谢谢,是的,这就是我目前拥有的(尽管不在问题的图片中)。不过,我希望的是在缩放窗口中删除主轴网格线(根据问题中的最后一行)
-
如果矩形的 zorder 低于散点图的 zorder 并且它们都位于相同的轴上,那么散点图将在矩形顶部可见。
标签: python matplotlib plot