简体   繁体   English

Matplotlib:inset_axes,缩放框未正确显示条形

[英]Matplotlib: inset_axes, zoom box not showing bars correctly

I'm trying to build a zoom box that should show a smaller section larger.我正在尝试构建一个缩放框,该缩放框应该显示较小的部分。

Unfortunately, the labels and bars are not positioned correctly in the box.不幸的是,标签和条在框中的位置不正确。 The bar of Test5 starts directly at the zero point and goes out of the graphic. Test5 的条形图直接从零点开始,走出图形。 The same problem exists with Test8. Test8 也存在同样的问题。

How can you move the labels and the bars so that everything is visible inside the box?您如何移动标签和条形以便在框内看到所有内容?

The picture here shows the current status.此处的图片显示了当前状态。 The code looks like this:代码如下所示:

fig, ax = plt.subplots(figsize=(10, 8))
overview_data_x = ['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6', 'Test7', 'Test8']
overview_data_y = [2500, 4100, 3900, 2000, 15, 75, 10, 25]

color = ['darkgrey', 'crimson', 'darkgreen', 'royalblue', 'orchid', 'y', 'peru', 'c']

ax.bar(overview_data_x, overview_data_y, color=color, align='center')
ax.set_ylabel('MB/s')

axins = inset_axes(ax, width="50%", height=1.5, loc=1)
axins.bar(overview_data_x, overview_data_y, color=color, align='center')

x1, x2 = 'Test5', 'Test8'
y1, y2 = 0, 100
axins.set_xlim(x1, x2) 
axins.set_ylim(y1, y2)

mark_inset(ax, axins, loc1=3, loc2=4, fc="none", ec="0.5")

When you draw a barplot, the bars extend from index-width/2 to index+width/2, where index is a whole number [0,1,...,N_of_bars-1].绘制条形图时,条形从 index-width/2 延伸到 index+width/2,其中 index 是整数 [0,1,...,N_of_bars-1]。 By default width is equal to 0.8, so the bars don't quite touch each other.默认情况下,宽度等于 0.8,因此条形之间不会完全接触。 If you want to see the whole bars in your inset, you therefore need to take into account the width of your bars:如果您想在插图中查看整个条形图,则需要考虑条形图的宽度:

fig, ax = plt.subplots(figsize=(10, 8))
overview_data_x = ['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6', 'Test7', 'Test8']
overview_data_y = [2500, 4100, 3900, 2000, 15, 75, 10, 25]

color = ['darkgrey', 'crimson', 'darkgreen', 'royalblue', 'orchid', 'y', 'peru', 'c']

ax.bar(overview_data_x, overview_data_y, color=color, align='center')
ax.set_ylabel('MB/s')

axins = inset_axes(ax, width="50%", height=1.5, loc=1)
axins.bar(overview_data_x, overview_data_y, color=color, align='center')

# BELOW IS THE ONLY LINE THAT I CHANGED
x1, x2 = overview_data_x.index('Test5')-0.5, overview_data_x.index('Test8')+0.5
y1, y2 = 0, 100
axins.set_xlim(x1, x2) 
axins.set_ylim(y1, y2)

mark_inset(ax, axins, loc1=3, loc2=4, fc="none", ec="0.5")

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM