使用matplotlib降低x轴的值

5

我应该如何绘制一个条形图,其中x轴的值按照从高到低的顺序排列?

例如:

为了举例说明,我的图表如下所示:

graph

我需要对图表进行排序,按照星期一(最高值),星期三,星期二(最小值)的顺序绘制图表。

这是我目前的进展:

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) 

简单的答案是,您需要对numpy.histogram输出的值进行排序,并跟踪表示一周中哪些天的索引。但是,如果没有一些示例代码,就无法给出明确的答案。请发布一个最小的现有示例。 - ebarr
2个回答

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轴同理)时,会自动“做正确的事情”。


请问您能描述一下每行代码的作用吗?我不太明白ax和plt.gca()是从哪里来的或代表什么。谢谢。 - user3521614
那段代码翻转了x轴,我的预期结果应该是将值从大到小降序排列,最大的值在左边,最小的值在最右边。 - user3521614
这两件事情有什么不同?请展示一个(最小的)例子,说明你现在正在做的事情是不起作用的。 - tacaswell

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接