[英]Descend x-axis values using matplotlib
如何繪制條形圖,其中 x 軸值按從高到低的降序排列?
例子:
出於示例目的,我的繪圖如下所示:
我需要圖表對其繪制星期一(最大值)、星期三、星期二(最小值)(分別)的位置進行排序
這是我到目前為止所擁有的:
x_axis = ['a','b','c'...'z']
y_axis = [#...#...#] number values for each letter in xaxis
def barplot(x_axis, y_axis): #x and y axis defined in another function
x_label_pos = range(len(y_axis))
plot.bar(x_label_pos, y_axis)
plot.yticks(range(0, int(max(y_axis) + 2), 2))
plot.xticks(x_axis)
# grab a reference to the current axes
ax = plt.gca()
# set the xlimits to be the reverse of the current xlimits
ax.set_xlim(ax.get_xlim()[::-1])
# call `draw` to re-render the graph
plt.draw()
如果將 x 限制設置為左值大於右值(與 y 軸相同), matplotlib
將“做正確的事”。
所以下面是一個最小的例子,可以滿足你的需要。 您的問題實際上與 matplotlib 無關,而只是根據需要重新排序輸入數據的一種情況。
import matplotlib.pyplot as plt
# some dummy lists with unordered values
x_axis = ['a','b','c']
y_axis = [1,3,2]
def barplot(x_axis, y_axis):
# zip the two lists and co-sort by biggest bin value
ax_sort = sorted(zip(y_axis,x_axis), reverse=True)
y_axis = [i[0] for i in ax_sort]
x_axis = [i[1] for i in ax_sort]
# the above is ugly and would be better served using a numpy recarray
# get the positions of the x coordinates of the bars
x_label_pos = range(len(x_axis))
# plot the bars and align on center of x coordinate
plt.bar(x_label_pos, y_axis,align="center")
# update the ticks to the desired labels
plt.xticks(x_label_pos,x_axis)
barplot(x_axis, y_axis)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.