How to change the plot size: Matplotlib, Seaborn, Plotly

Matplotlib

Method 1: Specifying figsize

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(24, 12))
ax = plt.axes()
plt.sca(ax)
plt.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5])

Note that the size gets applied in inches.

sca set the current axes.

Method 2: Using set_size_inches

import matplotlib.pyplot as plt
plt.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5])
fig = plt.gcf()
fig.set_size_inches(24, 12)

gcf stands for get current figure

Method 3: Using rcParams

This can be used when you want to avoid using the figure environment. Please note that the rc settings are global to the matplotlib package and making changes here will affect all plots (future ones as well), until you restart the kernel.

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (24,12)
plt.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5])

Here as well, the sizes are in inches.


Seaborn

Method 1: Using matplotlib axes

import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure(figsize=(24, 12))
ax = plt.axes()
sns.scatterplot(x =[1,2,3,4,5],y=[1,2,3,4,5], ax=ax)

This works for axes-level functions in Seaborn.

Method 2: Using rc

import seaborn as sns
sns.set(rc={'figure.figsize':(24,12)})
sns.scatterplot(x =[1,2,3,4,5],y=[1,2,3,4,5])

Again, this is a global setting and will affect all future plots, unless you restart the kernel.

Method 3: Using height and aspect ratio

This works for figure-level functions in seaborn.

import pandas as pd
import seaborn as sns

df = pd.read_csv('myfile.csv')
sns.pairplot(df,height = 12, aspect = 24/12)

Plotly

Method 1: Function Arguments in Plotly Express

import plotly.express as px
fig = px.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5], width=2400, height=1200)
fig.show()

Please note that instead of inches, the width and height are specified in pixels here.

Method 2: Using update_layout with Plotly Express

import plotly.express as px
fig = px.scatter(x =[1,2,3,4,5],y=[1,2,3,4,5])
fig.update_layout(
    width=2400,
    height=1200
)
fig.show()

Method 3: Using update_layout with Plotly Graph Objects

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[1,2,3,4,5],
    y=[1,2,3,4,5]
))

fig.update_layout(
    width=2400,
    height=1200)

fig.show()

If you are interested in data science and visualization using Python, you may find this course by Jose Portilla on Udemy to be very helpful. It has been the foundation course in Python for me and several of my colleagues.

You are also encouraged to check out further posts on Python on iotespresso.com.

Leave a comment

Your email address will not be published.