Home > Blockchain >  Matplotlib subplots does not set colors to bars individually
Matplotlib subplots does not set colors to bars individually

Time:08-29

I'm trying to draw bar plots as sub-plots using the code below. Even I give multiple colors it set first color for all bars.

fig, axes = plt.subplots(ncols=len(df_grp['season'].unique()), sharey=True, figsize=(30, 14))
fig.subplots_adjust(wspace=0)
for i, season in enumerate(df_grp['season'].unique()):
    d = df.loc[df['season'] == season, ['home_team', 'home_team_goal']]
    s = d.plot(kind='bar', x='home_team', ax=axes[i], xlabel='\n' season, legend=None, color=list('rgbk'))

See the screenshot below. enter image description here

CodePudding user response:

It's easier to use matplotlib directly then doing the plotting with pandas:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'season': np.repeat(range(2010, 2015), 4).astype(str),
                   'home_team': list('abcd') * 5,
                   'home_team_goal': np.random.randint(10, 30, 20)})

fig, axes = plt.subplots(ncols=len(df['season'].unique()), sharey=True, figsize=(20, 10))
fig.subplots_adjust(wspace=0)

for i, season in enumerate(df['season'].unique()):
    d = df.loc[df['season'] == season, ['home_team', 'home_team_goal']]
    axes[i].bar(d['home_team'], d['home_team_goal'], color=list('rgbk'))
    axes[i].set_xlabel('\n'   season)

enter image description here

  • Related