-
-
Notifications
You must be signed in to change notification settings - Fork 102
Programming: Moving away from pyplot
Joshua Newton edited this page Aug 22, 2020
·
1 revision
Matplotlib has two interfaces: pyplot (based on MATLAB) or object-oriented (OO) interface. Pyplot inteface is causing problems with backend on some headless stations. The purpose of this wiki is to explain how to refactor the code to a all OO interface. With this, figures are not displayed to the frontend, but saved. In this case, we utilize an instance of axes.Axes in order to render visualizations on an instance of figure.Figure.
OO Approach:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig = Figure()
FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3])
ax.set_title('hi mom')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('volts')
fig.savefig('test.png')
test:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig_disc = Figure()
FigureCanvas(fig_disc)
ax_disc = fig_disc.add_axes((0, 0, 1, 1))
# get percentile for automatic contrast adjustment
data_display = np.mean(data[xc - param.size_RL:xc + param.size_RL, :, :], axis=0).transpose()
percmin = np.percentile(data_display, 10)
percmax = np.percentile(data_display, 90)
# display image
ax_disc.matshow(data_display, cmap='gray', clim=[percmin, percmax], origin='lower')
ax_disc.set_title('Anatomical image')
# ax.autoscale(enable=False) # to prevent autoscale of axis when displaying plot
ax_disc.scatter(yc + param.shift_AP_visu, init_disc[0], c='yellow', s=50)
ax_disc.text(yc + param.shift_AP_visu + 4, init_disc[0], str(init_disc[1]) + '/' + str(init_disc[1] + 1),
verticalalignment='center', horizontalalignment='left', color='pink', fontsize=15)
fig_disc.savefig('fig_save_init_disc.png')
More info:
Editing the Wiki? If you're adding a new page or changing a title, be sure it fits the existing Wiki Structure.