這是我用來生成下面條形圖的資料和代碼:
import pandas as pd
import matplotlib.pyplot as plt
data = [["2019","Jan.", 2000,2200,-200],
["2019","Feb.", 1500,1400,100],
["2019","Dec.", 1200,1100,100],
["2020","Jan.", 1400,1300,100],
["2020","Dec.", 1300,1200,100]]
df = pd.DataFrame(data, columns=["Year", "Month", "incomes", "expenses", "Balance"])
df.plot.bar()
plt.show()

然而,我想df["Year"]用作主要的刻度標簽和df["Month"]次要的標簽,而不是序數。
這是怎么做的?
uj5u.com熱心網友回復:
您可以通過遍歷資料框來創建標簽,通過連接年和月來創建字串。
import pandas as pd
import matplotlib.pyplot as plt
data = [["2019", "Jan.", 2000, 2200, -200],
["2019", "Feb.", 1500, 1400, 100],
["2019", "Dec.", 1200, 1100, 100],
["2020", "Jan.", 1400, 1300, 100],
["2020", "Dec.", 1300, 1200, 100]]
df = pd.DataFrame(data, columns=["Year", "Month", "incomes", "expenses", "Balance"])
ax = df.plot.bar()
ax.set_xticks(range(len(df)))
ax.set_xticklabels([f"{month}\n{year}" for year, month in zip(df["Year"], df["Month"])], rotation=0)
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400812.html
標籤:蟒蛇-3.x 熊猫 matplotlib
