Plotting two dictionaries in one bar chart with Matplotlib [duplicate]

Deadly 提交于 2019-12-11 12:03:26

问题


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}

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)

回答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()


来源:https://stackoverflow.com/questions/45968359/plotting-two-dictionaries-in-one-bar-chart-with-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!