首页 > 解决方案 > 传递给 matplotlib 时按升序排序的列表

问题描述

我定义了一个 python 函数,它获取一个列表作为输入。我传递的列表按降序排列。我正在将此列表作为我的线图的x 轴。但是,matplotlib 正在按降序对其进行排序。我想保留降序。这是我的代码:

    def produce_curves_topK(self, topKs, metric):
        for i in range(len(clfs)):
            risk_df = self.risk_dfs[i]
            metrics = []
            for topk in topKs:
                risk_df_curr = risk_df.head(n=topk)
                # test_indices = list(risk_df_curr['test_indices'])
                y_pred_curr = list(risk_df_curr['y_pred'])
                # y_true_curr = list(self.y_test_df.loc[test_indices, self.target_variable])
                y_true_curr = list(risk_df_curr['y_test'])
                if metric == 'precision':
                    precision_curr = precision_score(y_true_curr, y_pred_curr)
                    metrics.append(precision_curr)
                else:
                    recall_curr = recall_score(y_true_curr, y_pred_curr)
                    metrics.append(recall_curr)

            # vals = {
            #     'topKs': topKs,
            #     'metrics': metrics
            # }
            # df = pd.DataFrame(vals, columns=['topKs', 'metrics'])

            # HERE IT IS BEING SORTED IN ASCENDING ORDER
            plt.plot(topKs, metrics, label=self.model_names[i], marker='o')

        plt.legend(loc='best')
        plt.xlabel('Top K')
        if metric == 'precision':
            plt.ylabel('Precision')
            plt.savefig('precisions_topK.png')
        else:
            plt.ylabel('Recall')
            plt.savefig('recalls_topK.png')
        plt.close()

# the list is originally in descending order
produce_curves_topK(topKs=[60, 50, 40, 30, 20, 10], metric='precision')

这是情节(x轴按升序排序 - 我希望它按降序排列在此处输入图像描述

标签: pythonsortingmatplotlib

解决方案


您可以抓住轴对象,然后将 xlim 设置为相反的顺序。

fig, ax = plt.subplots()
plt.plot(x,y)
ax.set_xlim(ax.get_xlim()[::-1])

这是一个例子:

import matplotlib.pyplot as plt

x = [60,50,40,30,20,10]
y = [0,1,2,3,4,5]
fig, ax = plt.subplots()

plt.plot(x,y)
ax.set_xlim(ax.get_xlim()[::-1])
plt.show()

推荐阅读