我正在嘗試創建一個情節
pd.crosstab(df['cardio'], df['cholesterol']).plot(kind = 'bar')
plt.xlabel('0 = No Heart Disease, 1 = Heart Disease Present')
plt.ylabel('Number of people')
#####plt.legend(['Above Normal','High', 'Normal'])
plt.legend(df['cholesterol'])
plt.title("Distribution w.r.t cholesterol")
plt.show()
資料框的膽固醇值分別為 1、2、3,分別表示正常、高于正常、遠高于正常。上面的代碼給legend 1, 2, 3. 有沒有辦法用自定義字串替換legend值,也就是說,我可以定義1應該在legend中顯示為“normal”,2為“above normal”和 3 為“遠高于正常水平”。提前致謝。
uj5u.com熱心網友回復:
資料是使用評論中的資訊獨立創建的。我還匯總了熊貓圖,因為您可以為軸設定標題和標簽。然后,您可以從創建的圖例中獲取句柄和標簽,并指定要替換的標簽。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import random
df = pd.DataFrame({'cardio': random.choices([0,1], k=100),
'cholesterol': random.choices([1,2,3], k=100)})
ax = pd.crosstab(df['cardio'], df['cholesterol']).plot(kind = 'bar',
title='Distribution w.r.t cholesterol',
xlabel='0 = No Heart Disease, 1 = Heart Disease Present',
ylabel='Number of people'
)
new_labels = ['Above Normal','High', 'Normal']
handler, _ = ax.get_legend_handles_labels()
ax.legend(handler, new_labels, loc='upper center', title='cholesterol')

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359784.html
標籤:Python 熊猫 数据框 matplotlib 数据科学
