Bookmarks

To try out

Matplotlib

Figure layout

  • use subfigures + subfigures to make publication level figures in one shot

    fig = plt.figure(layout='constrained', figsize=(10, 4))
    subfigs = fig.subfigures(nrows=1, ncols=2, 
    						 wspace=0.07, hspace=None,
    						 width_ratios=[1.5,1], 
    						 height_ratios=None)
     
     
    axsL = subfigs[0].subplots(nrows=1, ncols=2, 
    						   sharex=False, sharey=True)
    axsR = subfigs[1].subplots(nrows=1, ncols=2, 
    						   sharex=True, sharey=False)
  • subfigures guide (doc sheet)

  • subplot_mosaic for complicated axes - guide

     

axs = subfigs[0].subplot_mosaic(
"""
abc
""",
width_ratios=[1,0.75,1.5],
sharey=True
)
```

Figure axes

  • axis labels

    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
  • I prefer removing the axes and spine. despine from seaborn generally works well, but in some cases spines still remain so I switch of visibility for those

    sns.despine(ax=ax, trim=True, offset=5)

ax.spines’right’, ‘top’.set_visible(False)
```

  • more axes modifications

     
    ax.spines['bottom'].set_color('red')
    ax.spines['top'].set_color('red')
    ax.xaxis.label.set_color('red')
    ax.tick_params(axis='x', colors='red')
     
  • axis limits

    ax.axis([350, 700, 0, 1])
    ax.set_xlim()
    ax.xaxis.set_ticks()

Multiple x, y axis

  • guide - here

  • Make multiple y axis by:

    ax_r = ax.twinx()
    # use ax_r as normal
  • Make multiple x axis by using ax.twiny()

Plot

the workhorse - doc sheet

ax.plot(x,y,color='tab:orange')
ax.plot(x,y, dashes=[2, 2], label='__nolabel__', color='k') #dashed line

Fill between

  • Easy to make filled plots, highlight stimulus areas, etc
  • demo
ax.fill_between(x, 0, y, label='label', facecolor=('color', alpha)) # has no edge line
ax.fill_between(x, 0, y, label='label', color=('#000', 0.3)) # with a line edge

Ordering artists

  • Note: This does not work with twin axes

  • Probably works with other types of axes, not sure

  • Works with different plots. Higher zorder implies it will be on top1

  • Demo

    plot(..., zorder=10)

Labels

  • Changing location orientation of x and y labels

    ax.set_ylabel('Label', rotation=270)
    ax.yaxis.set_label_coords(1.12,0.5)

Colorbars

  • Colorbar tutorial

  • Placing colorbars

  • Colorbar tick labeling demo

  • Adding an colorbar to an axes:

    cbar = fig.colorbar(mpl.cm.ScalarMappable(norm= mpl.colors.Normalize(0, 1), cmap='viridis'), ax=ax, orientation='vertical', ticks=[0, 1], format=mpl.ticker.FixedFormatter(['min', 'max']))
  • Modifying cbar labels:

    cbar.set_label("Label", rotation=270)

Legends

  • a very nice guide for customizing legends (doc sheet)
  • use _nolegend_ to skip plots from appearing in legend2
  • you can hook it to subplots or subfigures or figures.
  • bbox_to_anchor coupled with loc is a good way of moving the legend to where you would like it in the plot.

example:

legend(legend_str, loc='outside upper right', frameon=False, bbox_to_anchor=(1.0, 0.96))

Text

  • To add annotations to the text - guide (doc sheet)

    ax.text(x,y,'$\mu=$%d'%(text), color=text_color, 
    		weight='bold', ha=align)

Saving figures

  • Typically, I save as a pdf as svg rarely works well for me with Affinity designer.
  • Using bbox_inches='tight' allows legends and other modifications that go beyond 1 in a normalized fig size.3
fig.savefig("figure.pdf", bbox_inches='tight')

Footnotes

  1. https://stackoverflow.com/questions/17431441/matplotlib-scatter-plot-to-foreground-on-top-of-a-contour-plot

  2. https://stackoverflow.com/questions/24680981/show-only-certain-items-in-legend - note, label=None did not work for me

  3. https://stackoverflow.com/a/71663610