【问题标题】:Descend x-axis values using matplotlib使用 matplotlib 降低 x 轴值
【发布时间】:2021-02-21 12:58:49
【问题描述】:

如何绘制条形图,其中 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) 

【问题讨论】:

  • 简单的答案是您需要按numpy.histogram 对输出的值进行排序,并跟踪代表一周中各天的索引。但是,如果没有一些示例代码,就不可能给你一个明确的答案。请发布一个您现在拥有的最小示例。

标签: python matplotlib plot


【解决方案1】:
# 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() 从哪里来或代表什么。谢谢。
  • 该代码颠倒了 x 轴,我的预期结果应该是从最大值到最小值,最大值在左边,最小值在最右边。
  • 这两件事有何不同?请展示一个(最小的)示例,说明您现在正在做什么但不起作用。
【解决方案2】:

所以下面是一个最小的例子,可以满足你的需要。您的问题实际上与 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()

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2013-01-15
    • 1970-01-01
    相关资源
    最近更新 更多