Matplotlib Figure Size

Matplotlib Figure Size

In Matplotlib, figure size is an important aspect of creating visually appealing plots. The figure size can greatly affect the readability and presentation of your plots. In this article, we will explore how to set the size of a figure in Matplotlib.

Set Figure Size

To set the size of a figure in Matplotlib, you can use the figure function and specify the size of the figure using the figsize parameter. The figsize parameter takes a tuple of two values representing the width and height of the figure in inches.

import matplotlib.pyplot as plt

# Create a figure with a specific size
plt.figure(figsize=(8, 6))

# Plot a simple line graph
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

# Display the plot
plt.show()

Output:

Matplotlib Figure Size

In this example, we create a figure with a size of 8 inches in width and 6 inches in height. When the plot is displayed, you will see that the figure has the specified dimensions.

Default Figure Size

By default, Matplotlib uses a predefined figure size for plots. You can change the default figure size for all plots in your script using the rcParams dictionary.

import matplotlib.pyplot as plt

# Change the default figure size
plt.rcParams['figure.figsize'] = (10, 8)

# Plot a simple line graph
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

# Display the plot
plt.show()

Output:

Matplotlib Figure Size

In this example, we set the default figure size to 10 inches in width and 8 inches in height. All subsequent plots in the script will use this default size unless explicitly specified.

Aspect Ratio

The aspect ratio of a figure is the ratio of its width to its height. You can control the aspect ratio of a figure by setting the aspect parameter when calling the imshow function.

import matplotlib.pyplot as plt
import numpy as np

# Generate random data
data = np.random.rand(10, 10)

# Display the data with a specific aspect ratio
plt.imshow(data, aspect=2)

# Display the plot
plt.show()

Output:

Matplotlib Figure Size

In this example, we set the aspect ratio of the plot to 2. This will make the width of the plot twice the height, resulting in a stretched appearance.

Subplots with Different Sizes

When creating subplots in Matplotlib, you can specify different sizes for each subplot by passing a list of width ratios to the gridspec_kw parameter of the subplots function.

import matplotlib.pyplot as plt

# Create subplots with different sizes
fig, axs = plt.subplots(2, 2, gridspec_kw={'width_ratios': [1, 2]})

# Plot data on each subplot
for ax in axs.flat:
    ax.plot([1, 2, 3, 4], [1, 4, 9, 16])

# Display the subplots
plt.show()

Output:

Matplotlib Figure Size

In this example, we create a 2×2 grid of subplots with the first subplot having half the width of the second subplot. This allows you to control the arrangement and size of subplots within a single figure.

Adjust Figure Size Dynamically

You can dynamically adjust the size of a figure by using the set_size_inches method on the figure object. This allows you to resize the figure after it has been created.

import matplotlib.pyplot as plt

# Create a figure with a specific size
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 9, 16])

# Adjust the figure size
fig.set_size_inches(10, 6)

# Display the plot
plt.show()

Output:

Matplotlib Figure Size

In this example, we create a figure and plot some data, then adjust the size of the figure to 10 inches in width and 6 inches in height before displaying the plot.

Save Figure with Specific Size

When saving a plot to a file, you can specify the size of the saved image by using the figsize parameter of the savefig function. This allows you to control the dimensions of the saved image.

import matplotlib.pyplot as plt

# Create a figure with a specific size
plt.figure(figsize=(8, 6))

# Plot a simple line graph
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

# Save the plot to a file with a specific size
plt.savefig('plot.png', figsize=(8, 6))

In this example, we create a figure with a size of 8 inches in width and 6 inches in height, then save the plot to a file with the same dimensions.

Figure Size in Seaborn

Seaborn is a popular data visualization library built on top of Matplotlib. Seaborn provides a high-level interface for creating attractive and informative statistical graphics. You can set the figure size in Seaborn using the set function from the seaborn module.

import matplotlib.pyplot as plt
import seaborn as sns

# Set the figure size in Seaborn
sns.set(rc={'figure.figsize':(8, 6)})

# Plot a simple bar plot
sns.barplot(x=['A', 'B', 'C', 'D'], y=[1, 2, 3, 4])

# Display the plot
plt.show()

Output:

Matplotlib Figure Size

In this example, we use Seaborn to create a bar plot and set the figure size to 8 inches in width and 6 inches in height using the rc parameter of the set function.

Specify Figure Size in Pandas

Pandas is a powerful data manipulation library that also provides functionality for creating plots using Matplotlib. You can set the figure size in a Pandas plot by passing the figsize parameter to the plot method.

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [4, 3, 2, 1]})

# Plot the DataFrame with a specific figure size
df.plot(kind='bar', figsize=(8, 6))

In this example, we create a DataFrame and plot it as a bar chart with a figure size of 8 inches in width and 6 inches in height.

Multiple Figures with Different Sizes

You can create multiple figures with different sizes in Matplotlib by calling the figure function multiple times and specifying the size for each figure.

import matplotlib.pyplot as plt

# Create the first figure with a specific size
plt.figure(figsize=(8, 6))
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

# Create the second figure with a different size
plt.figure(figsize=(6, 4))
plt.plot([1, 2, 3, 4], [1, 8, 27, 64])

# Display the plots
plt.show()

Output:

Matplotlib Figure Size

In this example, we create two figures with different sizes: the first figure is 8 inches in width and 6 inches in height, while the second figure is 6 inches in width and 4 inches in height.

Customize Figure Size in 3D Plot

You can customize the size of a 3D plot in Matplotlib by setting the figsize parameter when creating the figure. 3D plots have an additional dimension, so the figure size can greatly affect the appearance of the plot.

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

# Create a 3D plot with a specific figure size
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Plot 3D data
x = [1, 2, 3, 4]
y = [1, 2, 3, 4]
z = [1, 4, 9, 16]
ax.scatter(x, y, z)

# Display the plot
plt.show()

Output:

Matplotlib Figure Size

In this example, we create a 3D scatter plot with a figure size of 10 inches in width and 8 inches in height, which allows for better visualization of the 3D data.

Adjust Subplot Size

You can adjust the size of individual subplots within a figure by specifying the size of each subplot using the add_subplot function and the position parameter.

import matplotlib.pyplot as plt

# Create a figure with two subplots
fig = plt.figure()

# Add the first subplot with a specific size
ax1 = fig.add_subplot(121, position=[0.1, 0.1, 0.4, 0.8])

# Add the second subplot with a different size
ax2 = fig.add_subplot(122, position=[0.6, 0.1, 0.3, 0.8])

# Plot data on each subplot
ax1.plot([1, 2, 3, 4], [1, 4, 9, 16])
ax2.plot([1, 2, 3, 4], [1, 8, 27, 64])

# Display the subplots
plt.show()

Output:

Matplotlib Figure Size

In this example, we create a figure with two subplots, where the first subplot takes up 40% of the figure size and the second subplot takes up 30% of the figure size. This allows you to customize the size and position of subplots within a single figure.

Use Aspect Ratio in 3D Plot

When creating a 3D plot in Matplotlib, you can set the aspect ratio of the 3D axes by using the set_box_aspect method. This allows you to control the ratio between the x, y, and z axes in the 3D plot.

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

# Create a 3D plot with specific aspect ratio
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot([1, 2, 3, 4], [1, 4, 9, 16], [1, 8, 27, 64])
ax.set_box_aspect([2,1,1])

# Display the plot
plt.show()

Output:

Matplotlib Figure Size

In this example, we create a 3D plot and set the aspect ratio of the x-axis to be twice the size of the y and z axes. This allows you to customize the proportions of the 3D plot for better visualization.

Resize Figure in Jupyter Notebook

When working with Matplotlib in a Jupyter Notebook, you can resize the figure using the %matplotlib inline magic command and setting the figure size within the notebook cell.

%matplotlib inline
import matplotlib.pyplot as plt

# Set the figure size within the notebook cell
plt.figure(figsize=(10, 8))
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

In this example, we use the %matplotlib inline magic command to display plots within the Jupyter Notebook, and then set the figure size to 10 inches in width and 8 inches in height for the plot within the notebook cell.

Interactive Figure Sizing with Widgets

You can create interactive plots in Matplotlib using widgets from the ipywidgets library. This allows users to dynamically adjust the size of the figure using sliders or other interactive controls.

import matplotlib.pyplot as plt
import numpy as np
import ipywidgets as widgets
from IPython.display import display

# Create a function to update the figure size
def update_figure_size(width, height):
    plt.figure(figsize=(width, height))
    plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
    plt.show()

# Create interactive widgets for setting figure size
width_slider = widgets.FloatSlider(value=8, min=1, max=15, step=1, description='Width:')
height_slider = widgets.FloatSlider(value=6, min=1, max=15, step=1, description='Height:')
widgets.interactive(update_figure_size, width=width_slider, height=height_slider)

In this example, we create an interactive plot where users can adjust the width and height of the figure using sliders. As the user changes the slider values, the figure size is updated dynamically.

Matplotlib Figure Size Conclusion

In this article, we explored how to set the size of figures in Matplotlib to create visually appealing plots. By controlling the figure size, aspect ratio, and subplot sizes, you can customize the appearance of your plots to better communicate your data. Experiment with different figure sizes and aspect ratios to find the best visual representation for your plots. Matplotlib provides a variety of options for adjusting figure sizes, allowing you to create professional-looking plots for your data visualization needs.

Like(0)