'pandas plot bar with TWO column values as Xaxis
I have the following Data_Frame (this is how the data frame was printed):
Year Month incomes expenses balance
X
2022-1 2022 1 24037.25 22922.10 1115.15
2022-2 2022 2 25348.23 19150.95 6197.28
I would like to bar plot the last three columns as a function of the first two, the Year and Month. So far, all answers on the Stack Overflow didn't produce the right plot.
Any help?
Solution 1:[1]
Updated following the update of the question. Assuming the 3 columns are numeric:
df[['incomes', 'expenses', 'balance']].plot.bar()
Solution 2:[2]
The problem I encountered was that the ostensibly numeric columns were in fact of type 'objects'. Converting these to 'float' solved the problem and produced the right plot.
Here is the code:
df_joined['X'] = df_joined['Year'].astype(str) + '-' + df_joined['Month'].astype(str)
df_joined.set_index('X', inplace=True)
print(df_joined.dtypes)
df_joined['incomes']=df_joined['incomes'].astype(float)
df_joined['expenses']=df_joined['expenses'].astype(float)
df_joined['balance']=df_joined['balance'].astype(float)
print(df_joined.dtypes)
df_joined[['incomes', 'expenses', 'balance']].plot.bar()
plt.show()
produces the following print-out:
Year int64
Month int64
incomes object
expenses object
balance object
dtype: object
Year int64
Month int64
incomes float64
expenses float64
balance float64
dtype: object
and produces the following plot:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | MeirG |


