Matplotlib:插入轴,缩放框未正确显示条形图

2024-04-20 14:17:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个缩放框,它应该显示一个较小的区域或较大的区域

不幸的是,标签和条在框中的位置不正确。Test5的条形图直接从零点开始,并从图形中消失。Test8也存在同样的问题

如何移动标签和条,使框内的所有内容都可见

The picture here shows the current status. 代码如下所示:

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")

Tags: 区域dataoverviewbar标签axcolorcenter
1条回答
网友
1楼 · 发布于 2024-04-20 14:17:29

绘制条形图时,条形图从索引宽度/2延伸到索引+宽度/2,其中索引是一个整数[0,1,…,N个条形图-1]。默认情况下,“宽度”等于0.8,因此这些条不会相互接触。如果希望在插图中看到整个条形图,则需要考虑条形图的宽度:

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")

enter image description here

相关问题 更多 >