DBCerigo February 2016

Altering individual graphs in Pandas hist groupby plot

I'm plotting a frequencies group by countries in an iPython notebook using:

df['country'].hist(by=df['frequency'], bins=yr_bins)

But the resultant figure is badly formatted; Badly_formattedhist

Things I'd like/like to be able to define:

  • y axis log or not
  • sizing of individual graphs
  • x axis limits
  • auto layout
  • spacing between each individual graph so the labels don't over lap

Things I've realised so far:

  • the call to .hist outputs a 9x9 2d array of matplotlib.axes._subplots.AxesSubplot objects
  • all of these AxesSubplotss are embedded in a single figure


DBCerigo February 2016

Best working case so far:

  • For log or not: just using keyword log=True
  • Sizing of individual graphs and an auto layout:

    • Determine the number of groups: n = len(df.groupby('country')
    • Then use the combination of keywords layout=(row, column) and figsize(width, height):
      • Hard code number of columns to c, and desired width w and height h ofeach graph
      • Then use layout((n / c), c) and figsize=((c * w), (( (n/c) * h ))
  • Setting x axis limits: get the axes array by axes = df... then loop over the axes applying set_xlim(lim)
       for row in axes:
           for ax in row:
  • The spacing turnout of but if required then do:

    plt.subplots_adjust(wspace=0.5, hspace=1)

Post Status

Asked in February 2016
Viewed 1,098 times
Voted 14
Answered 1 times


Leave an answer