我们可以在给定约束的同时按升序改变xaxis吗

2024-05-01 22:02:20 发布

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

我画了一个条形图,在这个条形图中,我想按降序显示标签,而我的标签“五”应该总是最后一个。你知道吗

enter image description here

上面显示的是我使用下面的代码生成的原始图形。你知道吗

import matplotlib.pyplot as plt 

# x-coordinates of left sides of bars  
left = [1, 2, 3, 4, 5] 

# heights of bars 
height = [10, 24, 36, 40, 5] 

# labels for bars 
tick_label = ['one', 'two', 'three', 'four', 'five'] 

# plotting a bar chart 
plt.bar(left, height, tick_label = tick_label, 
        width = 0.8, color = ['red', 'green']) 

# naming the x-axis 
plt.xlabel('x - axis') 
# naming the y-axis 
plt.ylabel('y - axis') 
# plot title 
plt.title('My bar chart!') 

# function to show 
# function to show the plot 
plt.show

输出:

我希望x轴显示在descending order from one to four中,而我的fifth label应该始终显示在最后。 ()


Tags: ofthetoshowbarplt标签left
1条回答
网友
1楼 · 发布于 2024-05-01 22:02:20

IIUC,只需按降序绘制列表中的元素(最后一个除外)。这可以通过对列表的所有但最后一个元素进行排序,然后将最后一个元素附加到反向排序的列表中来实现。反向排序(降序)可以通过首先对列表进行排序,然后使用[::-1]进行反向排序来完成。如果这不是你想要的,请在下面留言

import matplotlib.pyplot as plt 

left = [1, 2, 3, 4, 5] 
height = [10, 24, 36, 40, 5] 
tick_label = ['one', 'two', 'three', 'four', 'five'] 

height_plot = sorted(height[:-1])[::-1] + height[-1:]

plt.bar(left, height_plot, tick_label = tick_label, 
        width = 0.8, color = ['red', 'green']) 

plt.xlabel('x - axis') 
plt.ylabel('y - axis') 
plt.title('My bar chart!') 
plt.show()

enter image description here


如果还要更改x轴记号标签,请执行以下操作

height_plot = sorted(height[:-1])[::-1] + height[-1:]
new_labels = tick_label[:-1][::-1] + tick_label[-1:]

plt.bar(left, height_plot, tick_label = new_labels, 
        width = 0.8, color = ['red', 'green']) 

enter image description here

相关问题 更多 >