Why Matplotlib Does Not Plot

Why matplotlib does not plot?

It could be a problem with the backend.
What is the output of
python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)'?

If it is the 'agg' backend, what you see is the expected behaviour as it is a non-interactive backend that does not show anything to the screen, but work with plt.savefig(...).
You should switch to, e.g., TkAgg or Qt4Agg to be able to use show. You can do it in the matplotlib.rc file.

@shashank: I run matplotlib both on 12.04 and 12.10 without problems. In both cases I use the Qt4Agg backend. If you don't have the matplotlibrc set, the default backend is used.
I'm sure that for Precise matplotlib repo was built with TkAgg. If the Quantal version has been built with e.g. Agg, then that would explain the difference

matplotlib does not show my drawings although I call pyplot.show()

If I set my backend to template in ~/.matplotlib/matplotlibrc,
then I can reproduce your symptoms:

~/.matplotlib/matplotlibrc:

# backend      : GtkAgg
backend : template

Note that the file matplotlibrc may not be in directory ~/.matplotlib/. In this case, the following code shows where it is:

>>> import matplotlib
>>> matplotlib.matplotlib_fname()

In [1]: import matplotlib.pyplot as p

In [2]: p.plot(range(20),range(20))
Out[2]: [<matplotlib.lines.Line2D object at 0xa64932c>]

In [3]: p.show()

If you edit ~/.matplotlib/matplotlibrc and change the backend to something like GtkAgg, you should see a plot. You can list all the backends available on your machine with

import matplotlib.rcsetup as rcsetup
print(rcsetup.all_backends)

It should return a list like:

['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg',
'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'agg', 'cairo', 'emf', 'gdk', 'pdf',
'ps', 'svg', 'template']

Reference:

  • Customizing matplotlib

matplotlib plot window won't appear

I'm not convinced this is a pandas issue at all.

Does

import matplotlib.pyplot as plt
plt.plot(range(10))
plt.show()

bring up a plot?

If not:

How did you install matplotlib? Was it from source or did you install it from a package manager/pre-built binary?

I suspect that if you run:

import matplotlib            
print matplotlib.rcParams['backend']

The result will be a non-GUI backend (almost certainly "Agg"). This suggests you don't have a suitable GUI toolkit available (I personally use Tkinter which means my backend is reported as "TkAgg").

The solution to this depends on your operating system, but if you can install a GUI library (one of Tkinter, GTK, QT4, PySide, Wx) then pyplot.show() should hopefully pop up a window for you.

HTH,

matplotlib does not show plot()

The labels must use parentheses such as plt.xlabel("text"), not assigned to a string with = like you have in your example code. Make the changes in your code, save the changes, quit and reopen Spyder or whatever interpreter you are running, then run the code again.

plt.figure(1)
plt.scatter(pf["age"], pf["friend_count"])
plt.xlabel("age")
plt.ylabel("friends count")
plt.title("Facebook Friends count by Age")
plt.show()

matplotlib does not plot when named arguments are passed

If you look at the source code for plot ,
it goes something like this:

def plot(*args, **kwargs):
...

The documentation does it make it clear that x,y arrays are mandatory , but if you pass x=[],y=[] , the plot function would recognise them as parts of kwargs and not the args. Plot expects two arrays as direct arguments without which it returns an empty object set.
These links would tell you more about them:

https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/
https://www.geeksforgeeks.org/args-kwargs-python/

Matplotlib not plotting anything

Two things to fix:

  1. The axis limits for all subplots.
  2. set_data requires lists of coordinates, not numbers!
import os
import matplotlib.pyplot as plt
import numpy as np
import matplotlib

N = 609
def gendat():

res = list(np.random.random_sample(size=609))
lens = list(np.random.random_sample(size=609))
loss = list(np.random.random_sample(size=609))
for i, (r, le, lo) in enumerate(zip(res,lens,loss)):
yield i, r, le , lo


figure, axis = plt.subplots(1,3, figsize=(15,5))

line1, = axis[0].plot([],[])
axis[0].set_xlabel("Episodes")
axis[0].set_ylabel("Average Reward")
axis[0].set_title("Reward")
axis[0].set_xlim(0, N)
axis[0].set_ylim(-10, 10)

line2, = axis[1].plot([],[])
axis[1].set_xlabel("Episodes")
axis[1].set_ylabel("Average Episode Length")
axis[1].set_title("Episode Length")
axis[1].set_xlim(0, N)
axis[1].set_ylim(-10, 10)

line3, = axis[2].plot([],[])
axis[2].set_xlabel("Episodes")
axis[2].set_ylabel("Average Loss")
axis[2].set_title("Loss")
axis[2].set_xlim(0, N)
axis[2].set_ylim(-10, 10)

line = [line1,line2,line3]

def init():
line[0].set_data([],[])
line[1].set_data([],[])
line[2].set_data([],[])

return line

figure.tight_layout()

def append_to_line(line, x, y):
xd, yd = [list(t) for t in line.get_data()]
xd.append(x)
yd.append(y)
line.set_data(xd, yd)
print(xd)

def animate(dat):
i, r, le, lo = dat

append_to_line(line[0], i, r)
append_to_line(line[1], i, le)
append_to_line(line[2], i, lo)

# FFwriter = matplotlib.animation.FFMpegWriter(fps=30, extra_args=['-vcodec', 'libx264'])
ani = matplotlib.animation.FuncAnimation(figure, animate, frames=gendat, interval=20, repeat=False)

plt.show()

ani.save("results.mp4",writer=FFwriter, dpi=500)

Matplotlib not plotting all points

OK, you were very, very close. I didn't realize how close until I tried it. The problem you had was that you made points a 3D array where each entry had a value. It needed to be a 2D array, 1000 x 3.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

points = []
for x in range(10):
for y in range(10):
for z in range(10):
points.append((x,y,z))

points = np.array(points)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:,0],points[:,1],points[:,2])
plt.show()

matplotlib Plot does not appear

You're missing plt.show() at the end.

import numpy as np
import matplotlib.pyplot as plt

# Generate a sequence of numbers from -10 to 10 with 100 steps in between
x = np.linspace(-10, 10, 100)
# Create a second array using sine
y = np.sin(x)
# The plot function makes a line chart of one array against another
plt.plot(x, y, marker="x")
plt.show()
pass

or, if you want to save it into a file

plt.savefig("my_file.png")


Related Topics



Leave a reply



Submit