如何绘制条形图,其中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)
答案 0 :(得分:4)
# 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轴相同)。
答案 1 :(得分: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()