Reputation: 1059
I defined a python function that gets, as input, a list. The list I am passing is sorted in descending order. I am making this list the x-axis of my line plot. However, matplotlib is sorting it back in descending order. I want to retain the descending order. Here is my code:
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')
And here is the plot (x-axis sorted in ascending order - I want it in descending order)
Upvotes: 0
Views: 422
Reputation: 658
You can grab the axes object and then set the xlim to be in reverse order.
fig, ax = plt.subplots()
plt.plot(x,y)
ax.set_xlim(ax.get_xlim()[::-1])
Here is an example:
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()
Upvotes: 1