My code works, however it just feels like it's a long work around to what should be a simpler solution. I've scoured the documentation for matplotlib but I can't seem to find any answer for what I'm looking for. My code is below
# --- Setting up the plot
plt.figure(figsize=(16,8))
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.ylim(0,8)
plt.ylabel("Total KPS", fontsize=20)
plt.xlabel("Year", fontsize=20)
# --- Making a copy of the original set, and counting the data
nyc = shootings[shootings.city == "New York"][["date","race","id"]]
nyc.date = pd.to_datetime(nyc.date).dt.strftime('%Y')
nyc.groupby("date").count()
# --- dividing the data by race counts into their own mini sets, however now they dont
# --- all have the same date identifiers
nyc_b = nyc[nyc.race == "B"].groupby("date").count()
nyc_w = nyc[nyc.race == "W"].groupby("date").count()
nyc_h = nyc[nyc.race == "H"].groupby("date").count()
# --- setting the labels for the bar graph
labels = [2015,2016,2017,2018,2019,2020,2021,2022]
# --- Creating a function to run the datasets above to create an array to feed as data
# --- and bottom lists for the graph
def func(x):
group = []
for i in range(2015,2023):
if len(x[x.index == str(i)]) < 1:
group.append(0)
else:
group.append(x[x.index == str(i)].id.values[0])
return group
# ---- running said data through the functions
groupa = func(nyc_b)
groupb = func(nyc_w)
groupc = func(nyc_h)
# --- Building the final bottom array to add to my third bar
bottomc = []
for i in range(len(groupa)):
addc = groupa[i] + groupb[i]
bottomc.append(addc)
# --- Plotting the bars
plt.bar(labels, groupa, width=.5, label="black")
plt.bar(labels, groupb, bottom=groupa, width=.5, label="white")
plt.bar(labels, groupc , bottom=bottomc, width=.5, label="hispanic")
plt.gca().yaxis.grid(color="grey")
plt.legend(fontsize=16)
This results with:
My question is, is there any, obvious Matplotlib functions that I am missing to come to this same result, or at least a... less ugly... way of coming to this same conclusion? This is my first time asking the community, if anything needs to be clarified please let me know