xoux
xoux

Reputation: 3494

How to create a plot in matplotlib without using pyplot

I've been using matplotlib for five months now on a daily basis, and I still find creation of new figures confusing.

Usually I create a figure with 2x2 subplots using, for example, somthing like:

import matplotlib.pyplot as plt
import itertools as it
fig,axes = plt.subplots(2,2)
axit = (ax for ax in it.chain(*axes))
for each of four data series I want to plot:
    ax = next(axit)
    ax.plot(...)

The question I have now is: how can operate completely independently of pyplot, ie, how can I create a figure, populate it with plots, make style changes, and only tell that figure to appear at the exact moment I want it to appear. Here is what I am having trouble with:

import matplotlib as mpl
gs = gridspec.GridSpec(2,2)
fig = mpl.figure.Figure()
ax1 = fig.add_subplot(gs[0])
ax1.plot([1,2,3])
ax2 = fig.add_subplot(gs[1])
ax2.plot([3,2,1])

After running the above, the only thing that comes to mind would be to use:

plt.draw()

But this does not work. What is missing to make the figure with the plots appear? Also, is

fig = mpl.figure.Figure()

all I have to do to create the figure without pyplot?

Upvotes: 20

Views: 10473

Answers (2)

agile
agile

Reputation: 77

This works for me without matplotlib.pyplot

import sys
from PyQt5 import QtWidgets
from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg as FigureCanvas)
from matplotlib.figure import Figure
import numpy as np

fig=Figure()
canvas=FigureCanvas(fig)
ax=canvas.figure.add_subplot(111)

x=np.arange(-5,5,0.1)
y=np.sin(x)

ax.plot(x,y)
canvas.show()

app=QtWidgets.QApplication(sys.argv)
app.exec()

enter image description here

Upvotes: 3

xnx
xnx

Reputation: 25518

You could attach a suitable backend to your figure manually and then show it:

from matplotlib.backends import backend_qt4agg  # e.g.
backend_qt4agg.new_figure_manager_given_figure(1, fig)
fig.show()

... but why not use pyplot?

Upvotes: 2

Related Questions