1

I am trying to plot using matplotlib with python 3.7.

This is my code:

import matplotlib
fig = matplotlib.pyplot.figure()
rect = fig.patch
rect.set_facecolor("green")
x = [3, 7, 8, 12]
y = [5, 13, 2, 8]
graph1 = fig.add_subplot(1, 1, axisbg="black")
graph1.plot(x, y, "red", linewidth=4.0)
matplotlib.pyplot.show()   

But I keep getting this error:

File "C:\Users\User\Anaconda3\lib\site-packages\matplotlib\axes\_subplots.py", line 72, in __init__
  raise ValueError('Illegal argument(s) to subplot: %s' % (args,))

ValueError: Illegal argument(s) to subplot: (1, 1)

What is the problem?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

2 Answers2

2

The problem is that add_subplot has three mandatory arguments, not two. The arguments are M = "number of rows", N = "number of columns", and P = "item selection". The last one (P) is the linear index in the MxN grid, going across.

Additionally, the axis_bg and axis_bgcolor arguments were deprecated in matplotlib 2.0.0 and removed in matplotlib 2.2.0. Instead, use facecolor or fc for short.

You probably wanted to do

graph1 = fig.add_subplot(1, 1, 1, fc="black")

That being said, if you want to create a single set of axes on a figure, I have generally found it easier to use plt.subplots to make the figure and axes in one shot:

fig, graph1 = plt.subplots(subplot_kw={'facecolor': 'black'}, facecolor='green')

For convenience, it is most common to import pyplot as plt, either with

import matplotlib.pyplot as plt

or with

from matplotlib import pyplot as plt

All combined, your code could end up looking like this:

from matplotlib import pyplot as plt

fig, graph1 = plt.subplots(subplot_kw={'facecolor': 'black'},
                           facecolor='green')

x = [3, 7, 8, 12]
y = [5, 13, 2, 8]
graph1.plot(x, y, "red", linewidth=4.0)
plt.show()   
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • it gives me now the eror :Unknown property axisbg – Eliza Romanski Aug 24 '18 at 10:50
  • @ElizaRomanski. The axis_bg axis_bgcolor were deprecated in matplotlib 2.0.0 and removed in matplotlib 2.2.0. Will update momentarily. – Mad Physicist Aug 24 '18 at 10:53
  • 1
    @ElizaRomanski because it only accepts only certain keyword arguments, [as per docs](https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes): **kwargs This method also takes the keyword arguments for Axes. – Chillie Aug 24 '18 at 10:55
0

from matplotlib docs:

add_subplot(*args, **kwargs)[source]

Add a subplot.

Call signatures:

add_subplot(nrows, ncols, index, **kwargs)

add_subplot(pos, **kwargs)

As far as I can tell you are not providing the index argument to the function.

Community
  • 1
  • 1
Chillie
  • 1,356
  • 13
  • 16