简体   繁体   中英

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. The same problem exists with 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]. By default width is equal to 0.8, so the bars don't quite touch each other. 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")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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