使用matplotlib降序x轴值
我想画一个柱状图,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)
2 个回答
0
下面是一个简单的例子,可以满足你的需求。其实你的问题和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()
10
# 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()
matplotlib
会自动处理你设置的坐标轴范围,如果你把x轴的左边界设置得比右边界大(y轴也是一样),它会“聪明地”调整显示的内容。