首页 > 解决方案 > 我们可以在给出约束的同时按升序更改 x 轴吗

问题描述

我绘制了一个条形图,我想在其中按降序显示标签,而我的标签-'五个'应该总是在最后。

在此处输入图像描述

上面显示的是我使用下面的代码生成的原始图表。

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应该始终位于最后。()

标签: pythonmatplotlib

解决方案


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

在此处输入图像描述


如果您还想更改 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']) 

在此处输入图像描述


推荐阅读