This is the data and code I use to generate the bar-chart below:
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()
I would like however to use df["Year"]
as the major tick-label and df["Month"]
as the minor one, rather than the ordinal number.
How is that done?
CodePudding user response:
You could create labels by iterating through the dataframe, creating strings by concatenating the year and the month.
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()