How to Change plot size in Matplotlib

Changing plot size in Matplotlib in Python comes in handy when working with large datasets with many features, and you want to make sure the statistical figures are easy to read. However, using matplotlib, you can easily change the plot size in Python. Meanwhile, when visualizing large data features on a plot, it is more likely to get overlaps. However, the default plot size might need more breathing space for clear labels and presentation. Here, the advantage of changing plot size contributes to its role. After resizing the canvas size, the labels have more breathing space, and the chart becomes more readable. By adjusting the figure size in Matplotlib, you can create a more spacious canvas for your chart, allowing the axes labels to display without overlapping. This article will explore the prevalent approaches to changing the plot size.

Getting started with plot size in Matplotlib

Matplotlib is a powerful Python library for data visualization. The library provides numerous tools to create insightful charts and graphs. Knowing how to change the plot size in Matplotlib is a valuable skill that can help create visually appealing plots to enhance readability or accommodate specific display requirements. However, you can easily change the size of your plots to enhance readability and presentation. By using the figure object, you can resize the overall plot.

  • It helps to call the plt.figure(figsize=(x,y)) function to set a large canvas (plot size) for your art (data).
  • Furthermore, Make charts and plots in visual form using the plt.plot() and show() function. It provides a concise way to create and customize a bar chart in Matplotlib. 
  • Set charts and plots’ properties (size, color, labels, legends). 
  • It allows you to present your insights more effectively.

The Default Plot

Let’s take an example that visualizes the market share of different companies using a bar chart. However, you’ve collected data on market share figures and want to create a bar chart to visualize the trend. Each market share will be plotted against the corresponding companies on the x-axis. 

By default, the Matplotlib library lays down a plot 6.4 inches in width and 4.8 inches in height. The below example illustrates the default plot in matplotlib.

import matplotlib.pyplot as plt
# companies and their market share (replace with your actual data)
companies = ['Nestle', 'Similac', 'Olpers', 'nido 1+ ']
market_share = [29,55,22,17]  # Market share percentages
# Create a figure with a default size
# Creating a bar chart 
plt.bar(companies, market_share, color='indigo', label='Market Share')
# Adding labels and title
plt.xlabel('Companies')
plt.ylabel('Market Share (%)')
plt.title('Companies Market Share')
# Adding legend
plt.legend()
# Display the plot
plt.show()

In the code above, Using the plot() function, the x and y-axis value data are displayed on the plot using the show() function.

Resizing the figure size of the plot Using figsize() parameter

To handle the overlapping problem and enhance the readability, resize the figure in Matplotlib using the figure() function. Here’s how it works; modify the above code with the following commands to change the size of the plot.

# Create a figure with a default size
fig=plt.figure(figsize=(8, 6))
#this will create the png file in your working directory
fig.savefig('resizing the plot.png', dpi=70)

The figsize() parameter lets us change the plot size in inches. We can use the figsize() parameter inside the figure object to resize the plot in Python. The syntax would be like this:

figure(figsize=(WIDTH_SIZE,HEIGHT_SIZE))

Using the figsize attribute, you can create visuals of the required size for your data. Meanwhile, the figsize parameter adjusts the figure size for a bar chart visualizing milk companies’ market share. However, changing the plot size line to (8, 6) using the figsize parameter means the chart will be 8 inches wide and 6 inches in height.

Additional Methods to resize the plot in Matplotlib

Updating the rcParams dictionary

Updating the rcParams dictionary approach allows us to modify the default setting for the plot size for all future plots on the script. However, using the ‘figsize’ parameter, we can change the default setting for the plot size.

Here the restaurant data creates a line plot visualizing the correlation between restaurant popularity and ratings. The popularity list represents the x-axis values, and the rating list represents the corresponding y-axis values. However, the rcParams attribute updates the default figure size for all plots to value(7,5). This method, however, ensures that the size of each figure remains consistent throughout a visualization project.

import matplotlib.pyplot as plt
# restaurant ratings and their popularity 
restaurants = ['LAL QILA RESTAURANT', 'Oishi Sushi', 'KOLACHI RESTAURANT', 'SHABAZ TIKA']
ratings = [4.5, 3.8, 4.2, 4.0]
popularity = [180, 130, 150, 130]
# Update the default figure size in rcParams
plt.rcParams['figure.figsize'] = (7, 5)  
# Creating a line plot
plt.plot(popularity, ratings, color='blue', marker='o', label='Ratings')
# Adding labels and title
plt.xlabel('Popularity')
plt.ylabel('Ratings')
plt.title('Restaurant Popularity vs Ratings')
# Adding legend
plt.legend()
# Display the plot
plt.show()

The above code sets the default figure size to 7 inches in width and 5 inches in height.

Using the set_size_inches() function

Using the set_size_inches() function, we can dynamically change the size of an existing plot. This technique is beneficial for adjusting the size of individual plots.

Using set_size_inches() provides a direct and precise way to adjust the figure size for a specific plot. However, a plot customizes to meet your plot size requirement using set_size_inches ().

The set_size_inches() function adjusts the figure size of the plot (bar chart). The plt.gcf() function returns the current figure, and the .set_size_inches(7, 5) parameter adjusts the figure size to be 7 inches wide and 5 inches height.

import matplotlib.pyplot as plt
#company market capitalization
companies = ['Tesla', 'Apple', 'Google', 'eBay', 'AliExpress']
market_cap = [900, 1400, 1000, 50, 100]  # Market capitalization 
# Creating a bar chart
plt.bar(companies, market_cap, color='green', label='Market Cap')
# Adding labels and title
plt.xlabel('Companies')
plt.ylabel('Market Capitalization (Billions $)')
plt.title('Company Market Capitalization')
# Adding legend
plt.legend()
# Adjusting the figure size
plt.gcf().set_size_inches(7, 5)  
# Display the plot
plt.show()

Using the set_figheight() function to change the plot height

The set_figheight() function can be used only to resize the height of the plot. In the code below, the set_figheight() function is used to set the height of the plot to 4 inches.

Here, the set_figheight() function is used to change the plot height of the bar chart. The plt.gcf() function returns the current figure, and .set_figheight(4) sets the figure height to 4 inches. However, with set_figheight(), you will mainly be able to resize the plot’s height, which sometimes comes in handy when adjusting the horizontal feature that may overlap due to more variables of your plots. Hence, the function provides breathing room for the plot.

import matplotlib.pyplot as plt
# cuisine popularity across different states
states = ['California', 'Texas', 'New York', 'Asia']
popularity = [9, 6, 5, 7]  # Popularity rating (out of 10)
# Creating a bar chart
plt.bar(states, popularity, color='orange', label='Popularity')
# Adding labels and title
plt.xlabel('States')
plt.ylabel('Popularity (out of 10)')
plt.title('Cuisine Popularity Across States')
# Adding legend
plt.legend()
# Changing the plot height using set_figheight()
plt.gcf().set_figheight(4)
# Display the plot
plt.show()

Output:

Using the set_figwidth() function to change the plot width

Similar to the set_figheight() function, the set_figwidth() function changes the width ratio of the plot. Therefore, in the code below, the set_figwidth() function sets the width of the plot to 6 inches.

import matplotlib.pyplot as plt
# courier tracking service performance (replace with your actual data)
services = ['DHL', 'Century Express', 'Leopards', 'FedEx']
delivery_time = [3, 4, 2,5]  # Average delivery time in days
# Creating a bar chart
plt.bar(services, delivery_time, color='Red', label='Delivery Time')
# Adding labels and title
plt.xlabel('Courier Tracking Services')
plt.ylabel('Average Delivery Time (Days)')
plt.title('Courier Tracking Service Performance')
# Adding legend
plt.legend()
# Changing the plot width using set_figwidth()
plt.gcf().set_figwidth(6)
# Display the plot
plt.show()

Here, the set_figwidth() function is used to change the plot width of the bar chart. Meanwhile, the plt.gcf() function returns the current figure, and .set_figwidth(6) sets the figure width to 6 inches.

However, using set_figwidth() allows you to resize the vertical ratio of the visual. This is useful for ensuring that your visualizations present clearly and readably and allow for more breathing room when plotting data.

Conclusion

In this article, you learned how to resize the figures in a Matplotlib plot – explored various methods to change the plot size in Matplotlib. Each method has advantages and uses and allows us to create and modify plots according to our needs. Using the figsize attribute, you can change the size of a plot. However, following this, you learned how to adjust the size of Matplotlib plots using the set_figheight() and set_figwidth() functions. Last but not least, you learned how to change a Matplotlib chart’s size using rcParams. By implementing these methods, you will improve your Python programming skills. For any queries, contact us!

Leave a Comment

Your email address will not be published. Required fields are marked *