
使用舍入數值註釋Pandas 條形圖
在Pandas 條形圖中,使用相應的數值註釋條形可以增強數據可視化並提供對圖數據的深入了解。為了解決這個問題,讓我們考慮一個具有隨機值的 DataFrame:
1 2 3 4 | import pandas as pd
import numpy as np
df = pd.DataFrame({ 'A' : np.random.rand(2), 'B' : np.random.rand(2)}, index=[ 'value1' , 'value2' ])
|
登入後複製
挑戰:我們如何用舍入數值註解條形,類似於範例圖片?
解決方案:
直接存取軸的補丁擷取條形高度:
1 2 3 4 5 6 7 | import matplotlib.pyplot as plt
ax = df.plot(kind= 'bar' )
for p in ax.patches:
height = p.get_height()
label = round (height, 2)
ax.annotate(label, (p.get_x() * 1.005, p.get_height() * 1.005))
|
登入後複製
此方法從patch 物件取得條形高度,並使用舍入值註解條形。根據需要調整字串格式和偏移量以使註解居中。
程式碼範例:
1 2 3 4 5 6 7 8 9 10 11 12 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({ 'A' : np.random.rand(2), 'B' : np.random.rand(2)}, index=[ 'value1' , 'value2' ])
ax = df.plot(kind= 'bar' )
for p in ax.patches:
height = p.get_height()
label = round (height, 2)
ax.annotate(label, (p.get_x() * 1.005, p.get_height() * 1.005))
plt.show()
|
登入後複製
以上是如何用四捨五入的數值註解 Pandas 長條圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!