python - 传递给 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')
解决方案
您可以抓住轴对象,然后将 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()
推荐阅读
- ionic-framework - Ionic 3 更改离子卡头填充不会覆盖现有的
- django - Django:名称未显示在下拉列表中
- python - 在 defaultdict 中使用构造函数是否有效
- generics - Dart 2 runtimeType 和具体化泛型 - Java 类
相等的 - php - 在 Laravel/Lighthouse GraphQL API 中实现搜索功能
- javascript - 如何使用会话变量时间在 JavaScript 中显示测验计时器
- php - 如果在数据库中更新,则在网页中显示并自动更新 MySQL DB 的值
- c++ - 在 OpenGL ES 2.0 中应用高斯模糊时如何修复奇怪的伪影
- javascript - `this` 在解构参数函数中使用时未定义
- flutter - StatelessWidget 中的 build 方法是什么