背景關系:我正在繪制幾個模型的準確度值,并且我想在每個模型(條形圖)上顯示準確度值(來自串列結果)。考慮到我從最高準確度排序到最低準確度,我怎么能做到這一點?謝謝!
results = [lr_cv[1],svm_cv[1], decision_tree[1],score_log_reg_pca,nb_cv[1]] #colocar lista dos modelos feitos
names = ["Logistic Regression","SVM", "Decision Tree","Logistic Regression with PCA","Naive Bayes"] #colocar nomes para o grafico
df_new = pd.DataFrame(list(zip(names, results)), columns= ["Model","Accuracy"])
df_sorted = df_new.sort_values("Accuracy")
df_sorted.index=df_sorted.Model
plt.figure(figsize=(12,7))
ax = df_sorted.plot(kind="barh", facecolor="#AA0000",figsize=(15,10), fontsize=12)
ax.spines["bottom"].set_color("#CCCCCC")
ax.set_xlabel("Accuracy", fontsize=12)
ax.set_ylabel("Model",fontsize=12)
plt.title("Compara??o de modelos para Classifica??o")

uj5u.com熱心網友回復:
如果我理解正確,您想在每個欄的頂部添加一些文本,以顯示每個模型實作的準確度的實際值。您可以使用(documented here )的text()方法來完成。我已按如下方式修改了您的代碼(為準確性使用了一些虛擬值):ax()
import pandas as pd
import matplotlib.pyplot as plt
results = [lr_cv[1],svm_cv[1], decision_tree[1],score_log_reg_pca,nb_cv[1]] #colocar lista dos modelos feitos
names = ["Logistic Regression","SVM", "Decision Tree","Logistic Regression with PCA","Naive Bayes"] #colocar nomes para o grafico
df_new = pd.DataFrame(list(zip(names, results)), columns= ["Model","Accuracy"])
df_sorted = df_new.sort_values("Accuracy")
df_sorted.index=df_sorted.Model
plt.figure(figsize=(12,7))
ax = df_sorted.plot(kind="barh", facecolor="#AA0000",figsize=(15,10), fontsize=12)
gap = 0.015 # Space between the text and the end of the bar
# You have to call ax.text() for each bar
# They are already sorted and you need the index of the bar
for i, v in enumerate(df_sorted.Accuracy):
ax.text(v gap, i, str(v), color='blue') # Place the text at x=v gap and y= idx
ax.spines["bottom"].set_color("#CCCCCC")
ax.set_xlabel("Accuracy", fontsize=12)
ax.set_ylabel("Model",fontsize=12)
plt.title("Compara??o de modelos para Classifica??o")
另一種選擇是改編代碼并注意使用plot()pandas的方法,即Axes.bar_label()如下:
import pandas as pd
import matplotlib.pyplot as plt
results = [lr_cv[1],svm_cv[1], decision_tree[1],score_log_reg_pca,nb_cv[1]] #colocar lista dos modelos feitos
names = ["Logistic Regression","SVM", "Decision Tree","Logistic Regression with PCA","Naive Bayes"] #colocar nomes para o grafico
df_new = pd.DataFrame(list(zip(names, results)), columns= ["Model","Accuracy"])
df_sorted = df_new.sort_values("Accuracy")
df_sorted.index=df_sorted.Model
plt.figure(figsize=(12,7))
fig, ax = plt.subplots() # get ax handle
bars = plt.barh(df_sorted.Model, df_sorted.Accuracy) # Plot barh
ax.bar_label(bars) # Set the labels
ax.spines["bottom"].set_color("#CCCCCC")
ax.set_xlabel("Accuracy", fontsize=12)
ax.set_ylabel("Model",fontsize=12)
plt.title("Compara??o de modelos para Classifica??o")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/480627.html
標籤:Python matplotlib
