Moh*_*Ali 2 python plot matplotlib
问题是我需要在图中的特定区域绘制虚线矩形覆盖三个子图,以显示该覆盖部分的重要性,如下图所示。
我尝试使用一些使用“add-patch”的在线代码,但是,矩形出现在一个子图上并压缩该子图的条形。
ax0.add_patch(patches.Rectangle((147,100),100,300,linewidth=1,edgecolor='r',facecolor='none'))
Run Code Online (Sandbox Code Playgroud)
这是代码:
bins =[50, 100,150, 200,250,300,350]
y= [55,75,85,90,120,110,115,140,145,160,170,181,185,175,190,210,220,250,280,290,320]
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3)
colors = ['r','k','b']
ax0.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[0])
ax1.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[1])
ax2.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[2])
fig.subplots_adjust(hspace=0.6)
ax0.add_patch(patches.Rectangle((147, 100), 100, 300, linewidth=1, edgecolor='r', facecolor='none'))
plt.show()
Run Code Online (Sandbox Code Playgroud)
我将使用变换(请参阅变换教程)来生成在 x 方向上与数据部分对齐以及在 y 方向上与图形部分对齐的坐标。
bins =[50, 100,150, 200,250,300,350]
y= [55,75,85,90,120,110,115,140,145,160,170,181,185,175,190,210,220,250,280,290,320]
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, sharex=True)
colors = ['r','k','b']
ax0.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[0])
ax1.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[1])
ax2.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[2])
fig.subplots_adjust(hspace=0.6)
xmin, xmax = 150,250
trans = matplotlib.transforms.blended_transform_factory(ax0.transData, fig.transFigure)
r = matplotlib.patches.Rectangle(xy=(xmin,0), width=xmax-xmin, height=1, transform=trans,
fc='none', ec='b', lw=2)
fig.add_artist(r)
plt.show()
Run Code Online (Sandbox Code Playgroud)
编辑 如果您只想将框扩展到顶部轴的顶部和底部轴的底部,您还可以使用变换来获取图形坐标中的这些位置:
bins =[50, 100,150, 200,250,300,350]
y= [55,75,85,90,120,110,115,140,145,160,170,181,185,175,190,210,220,250,280,290,320]
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3, sharex=True)
colors = ['r','k','b']
ax0.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[0])
ax1.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[1])
ax2.hist(y, bins, histtype='bar', stacked=True, rwidth=0.8, color = colors[2])
fig.subplots_adjust(hspace=0.6)
xmin, xmax = 150,250
_,top = fig.transFigure.inverted().transform(ax0.transAxes.transform([0,1]))
_,bottom = fig.transFigure.inverted().transform(ax2.transAxes.transform([0,0]))
trans = matplotlib.transforms.blended_transform_factory(ax0.transData, fig.transFigure)
r = matplotlib.patches.Rectangle(xy=(xmin,bottom), width=xmax-xmin, height=top-bottom, transform=trans,
fc='none', ec='C0', lw=5)
fig.add_artist(r)
plt.show()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
942 次 |
最近记录: |