使用Matplotlib在一个条形图中绘制两个字典 [英] Plotting two dictionaries in one bar chart with Matplotlib

查看:220
本文介绍了使用Matplotlib在一个条形图中绘制两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要使用Matplotlib在同一条形图中绘制的字典:

I have these two dictionaries that I want to plot in the same bar chart using Matplotlib:

accuracy_pre = {"Random Forest": rf_accuracy_score, "Logistic Regression": log_accuracy_score, "KNN": knn_accuracy_score}

accuracy_post = {"Random Forest": gs_rf_accuracy_score, "Logistic Regression": gs_logmodel_accuracy_score, "KNN": knn_accuracy_score_iter}

字典值是整数变量.两个词典具有相同的键,因此总共会有6个小节,但是属于同一键的那些将彼此相邻. 我可以创建两个单独的条形图,但是很难将它们组合在一起.有人可以帮我吗?

The dictionary values are integer variables. Both dictionaries have the same keys, so there will be 6 bars in total, but those belonging to the same key will be right next to each other. I'm able to create two separate bar charts, but I have trouble putting them together in one. Could someone help me?

这是我已经拥有的条形图的代码:

This is the code for the bar chart I already have:

X = np.arange(len(accuracy_pre))
plt.bar(X, accuracy_pre.values(), align='center', width=0.5)
plt.xticks(X, accuracy_pre.keys()) 
plt.title("Accuracy score - before grid search", fontsize=17)
plt.ylim(0, 1)

推荐答案

我稍微调整了代码以获得所需的绘图.希望这会有所帮助!

I tweaked your code a bit to get the desired plot. Hope this helps!

import numpy as np
import matplotlib.pyplot as plt

#sample data
accuracy_pre = {"Random Forest": 1, "Logistic Regression": 2, "KNN": 3}
accuracy_post = {"Random Forest": 4, "Logistic Regression": 5, "KNN": 6}

X = np.arange(len(accuracy_pre))
ax = plt.subplot(111)
ax.bar(X, accuracy_pre.values(), width=0.2, color='b', align='center')
ax.bar(X-0.2, accuracy_post.values(), width=0.2, color='g', align='center')
ax.legend(('Pre Accuracy','Post Accuracy'))
plt.xticks(X, accuracy_pre.keys())
plt.title("Accuracy score", fontsize=17)
plt.show()

这篇关于使用Matplotlib在一个条形图中绘制两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆