I am trying to create a stacked bar plot. The code that I provide is pretty much what I want to do, i.e. have 12 x-values, one for each month, with 4 bars on each group of bars, one for every year. The only difference that I am trying to achieve is to have the bars stacked, with different colors coming from a color dictionary, one for each PC value. So the final plot, should have the exact number of bars, on the same exact positions, but each bar should be a stacked version of the current one. Is this even possible? If that's not possible and you have other ideas of how someone could visually represent the change and amount of the PC values for each month, each year, I would be glad to hear your suggestions
import pandas as pd
import random
import matplotlib.pyplot as plt
N=100
pc_col = [random.randint(1,7) for i in range(N)]
year_col = [random.randint(2020,2023) for i in range(N)]
month_col = [random.randint(1,12) for i in range(N)]
data = {'PC': pc_col, 'Year': year_col, 'Month': month_col}
data = pd.DataFrame(data)
counts = data.groupby(['Month', 'Year']).size().unstack()
counts.plot(kind='bar')
plt.xlabel('Month')
plt.ylabel('Count')
plt.title('Counts by Month and Year')
plt.show()
I have tried the stacked parameter with different group_by methods, but it doesn't seem to be actually doing what I want. I also have found this Pandas: Stacked bar plot with adjacent bars but in that way, the x-tick labels are misplaced. I have also found this Multiple stacked bar plot with pandas but in my case I don't know by default how many years the dataset will have