146

How can I modify the size of the output image of the function pandas.DataFrame.plot?

I tried:

plt.figure(figsize=(10, 5))

and

%matplotlib notebook

but none of them work.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
mommomonthewind
  • 4,390
  • 11
  • 46
  • 74

3 Answers3

269

Try the figsize parameter in df.plot(figsize=(width,height)):

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));

Enter image description here

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));

Enter image description here

The size in figsize=(5,3) is given in inches per (width, height).

An alternative way is to set desired figsize at the top of the Jupyter Notebook, prior to plotting:

plt.rcParams["figure.figsize"] = (10, 5)

This change will affect all the plots, following this statement.


As per explanation why it doesn't work for the OP:

plt.figure(figsize=(10,5)) doesn't work because df.plot() creates its own matplotlib.axes.Axes object, the size of which cannot be changed after the object has been created. For details please see the source code. Though, one can change default figsize prior to creation, by changing default figsize with plt.rcParams["figure.figsize"] = (width, height)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72
27

If you want to make a change to the whole notebook global:

import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
kvoki
  • 412
  • 5
  • 12
4

Try this:

import matplotlib as plt

After importing the file we can use the Matplotlib library, but remember to use it as plt:

df.plt(kind='line', figsize=(10, 5))

After that, the plot will be done and the size increased. In figsize, the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 6
    This is a terrible answer, which results in `AttributeError: 'DataFrame' object has no attribute 'plt'`. `pandas` imports `matplotlib` as a dependency, and the correct way to use `pandas.DataFrame.plot` to adjust `figsize` is shown in the [accepted answer](https://stackoverflow.com/a/51174822/7758804). `kind='line'` is not required, because it is the default. As the answer is blatantly incorrect, the fact it has any upvotes undermines the credibility of voting system. The correct import is `import matplotlib.pyplot as plt` as shown in the matplotlib Usage Guide. – Trenton McKinney Sep 22 '21 at 04:14
  • `import matplotlib as mpl` where `mpl` is the correct alias, not `plt`. [matplotlib Usage Guide](https://matplotlib.org/stable/tutorials/introductory/usage.html#splitting-lines-into-smaller-chunks) – Trenton McKinney Sep 22 '21 at 04:22