[英]pandas - How to covert an object index to numeric form for axis units?
我正在嘗試注釋我在 seaborn 中編碼的簡單條形圖。 問題是索引值無法轉換為軸單位。 我不確定為什么會發生這種情況,因為我已經在 matplotlib 中注釋了之前的圖表。 這是一個示例數據框:
# Note Q5 is the index
print(df)
Q5 Man Woman
A 50 55
B 10 11
C 20 30
代碼很簡單。 基於 Q5 作為索引,我在兩個單獨的子圖中繪制了男性和女性的值。 現在是注釋部分。 我在這里簡化了復制的代碼並跳過了 for 循環,但是說我使用Man
的“A”的第一個值作為注釋。
fig, ax = plt.subplots(2,1, figsize=(6, 8))
sb.barplot(x=df.Man, y=df.index, data=df, color='lightblue', ax=ax[0])
ax[0].annotate(format(df.Man["A"], xy=(age_occu.Man["A"], "A"))
# And I get this error
matplotlib.units.ConversionError: Failed to convert value(s) to axis units: 'A'
像往常一樣,我嘗試了其他幾種方法,比如沒有提到“A”作為 y 參數,而是將 0 指定為最頂部的 y 條目。 但我沒有克服這個錯誤。
注意:同時保存 plot 會返回相同的錯誤。
這是因為 annotate() 無法將“A”識別為坐標。 您需要檢索 plot 中數據的實際位置:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
# Note Q5 is the index
df = pd.DataFrame({'Man':[50, 10, 20], 'Woman':[55,11,30]}, index = pd.Index(['A','B','C'], name='Q5'))
fig, ax = plt.subplots(2,1, figsize=(6, 8))
s = sb.barplot(x=df.Man, y=df.index, data=df, color='lightblue', ax=ax[0])
for i in range(len(df)):
ax[0].annotate(s.patches[i].get_width(),
xy=(s.patches[i].get_width(),
s.patches[i].get_y() + s.patches[i].get_height()/2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.