Python Forum
Color Formatting for Bar Graphs in a for loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Color Formatting for Bar Graphs in a for loop (/thread-32050.html)



Color Formatting for Bar Graphs in a for loop - adamszymanski - Jan-17-2021

Hello,

I am trying to create a set of bar graphs using a code shared with me by a colleague. I am quite new to python so I am trying to use this code to learn the ins and outs of data visualization.

My issue is that the code works perfectly for line graphs, giving multiple lines plotted in different colors according to their identifier variable, here called "category". However, when I try to adapt the code for building a multiple bar graph or a stacked bar graph, the data are all plotted in the same color as if the code no longer recognizes different identifier variables.

First, the dataframe is converted into a panel format using the melt function. Essentially the identifier variables are moved onto a single column (named "categories") alongside another column listing the corresponding values (named "df_title") for a given year and identifier.

panel_df = df.melt(id_vars='Year', var_name='categories').rename(columns = {'value':df_title})
Then, after defining a custom palette and set style, the graph is plotted using a for loop.

sns.set_style(standard_style)
fig, ax = plt.subplots(constrained_layout=True)
for key, grp in panel_df.groupby(['categories']):
    ax = grp.plot(ax=ax, kind='bar', x='Year', y=df_title, label=key, stacked=True,)
plt.legend(loc='lower center')
plt.legend(bbox_to_anchor=(0, -0.25), loc='upper left', borderaxespad=0., ncol=2, fancybox=True, shadow=True, fontsize=11.5)
plt.show()
It would be hugely appreciated if someone could help me understand where the problem arises from. Is there a reason why setting kind='bar' should throw off the code? It seems strange why it would work so well for line graphs but not for bar graphs.

Thanks


RE: Color Formatting for Bar Graphs in a for loop - jefsummers - Jan-31-2021

I think you want to set the theme differently. I use matplotlib and not seaborn, but the seaborn docs cover this here