Python Forum
Color Formatting for Bar Graphs in a for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Color Formatting for Bar Graphs in a for loop
#1
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
Reply
#2
I think you want to set the theme differently. I use matplotlib and not seaborn, but the seaborn docs cover this here
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Turtle Star Fill Color Yellow-White Interchanging Color Effect codelab 9 997 Oct-25-2023, 09:09 AM
Last Post: codelab
  Plot several graphs on the same row Menthix 1 1,041 Mar-18-2022, 05:47 PM
Last Post: deanhystad
  grouped bar graphs tobiasfw 1 1,404 Feb-22-2022, 02:25 PM
Last Post: deanhystad
  Python Matplotlib: How do I save (in pdf) all the graphs I create in a loop? JaneTan 1 8,867 Feb-28-2021, 06:20 PM
Last Post: Larz60+
  How to merge strings through graphs Den 6 3,437 Jun-29-2020, 07:07 AM
Last Post: Den
  Tranforming into .exe with Matplotlib (graphs) ericvrocha 0 2,914 Oct-14-2019, 06:54 PM
Last Post: ericvrocha
  Little Help With Graphs ericvrocha 5 3,178 Oct-14-2019, 12:07 PM
Last Post: buran
  Drawing graphs with matplotlib JRod 5 4,711 Jul-31-2017, 10:00 AM
Last Post: JRod

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020