avatarEbrahim Mousavi

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3979

Abstract

stinguish between different data series in your plot. You can add a legend using the <code>legend()</code> function:</p><div id="e20f"><pre>y2 = [<span class="hljs-number">15</span>, <span class="hljs-number">25</span>, <span class="hljs-number">20</span>, <span class="hljs-number">35</span>]

plt.plot(x, y, label=<span class="hljs-string">'Product A'</span>) plt.plot(x, y2, label=<span class="hljs-string">'Product B'</span>) plt.xlabel(<span class="hljs-string">'Time (months)'</span>) plt.ylabel(<span class="hljs-string">'Sales (units)'</span>) plt.title(<span class="hljs-string">'Sales Comparison'</span>) plt.legend(loc=<span class="hljs-string">'upper left'</span>) plt.show()</pre></div><p id="a80e"><b>Output:</b></p><figure id="f99c"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ryvGsCJfcs4RqkOVl1DQog.png"><figcaption></figcaption></figure><p id="e416"><b>In this example:</b></p><ul><li><code>label='Product A'</code> and <code>label='Product B'</code> specify the labels for the two lines.</li><li><code>plt.legend(loc='upper left')</code> positions the legend in the upper left corner of the plot.</li></ul><p id="fb75">You can position the legend using various options like <code>'upper right'</code>, <code>'lower left'</code>, <code>'center'</code>, or even by specifying coordinates.</p><h2 id="ef6e">Adding Gridlines</h2><p id="5eb2">Gridlines make it easier to read values off the plot. You can add them with the <code>grid()</code> function:</p><div id="1f48"><pre>plt.plot(x, y) plt.xlabel(<span class="hljs-string">'Time (months)'</span>) plt.ylabel(<span class="hljs-string">'Sales (units)'</span>) plt.title(<span class="hljs-string">'Sales Over Time'</span>) plt.grid(<span class="hljs-literal">True</span>) plt.show()</pre></div><p id="3bd0"><b>Output:</b></p><figure id="8eda"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*gYkd5pD744DQ6BO6F7Vatg.png"><figcaption></figcaption></figure><p id="c876">Setting <code>plt.grid(True)</code> turns on the gridlines, and you can further customize them by adjusting their style, color, and width:</p><div id="2a7b"><pre>plt.grid(color=<span class="hljs-string">'gray'</span>, linestyle=<span class="hljs-string">'--'</span>, linewidth=<span class="hljs-number">0.5</span>)</pre></div><p id="b89c">Please try the above code and see the result of that.</p><h1 id="5cde">2. Plot Customization</h1><p id="c93d">Customizing your plot’s dimensions, axes, ticks, and adding annotations can greatly enhance its readability and aesthetic appeal.</p><h2 id="e1a3">Adjusting Plot Dimensions</h2><p id="6922">You can adjust the size of your plot using the <code>figsize</code> parameter in <code>plt.figure()</code>:</p><div id="9e2d"><pre>plt.figure(figsize=(<span class="hljs-number">8</span>, <span class="hljs-number">4</span>)) plt.plot(x, y) plt.title(<span class="hljs-string">'Sales Over Time'</span>) plt.show()</pre></div><p id="3d11"><b>Output:</b></p><figure id="8d30"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*AYWZKmKuo6y1p2p0IL3KnA.png"><figcaption></figcaption></figure><p id="ccdb">This example creates a plot that is <b>8 inches wide and 4 inches tall</b>.</p><h2 id="d418">Changing Axes Limits</h2><p id="2274">Sometimes, you might want to set specific limits for your x and y axes:</p><div id="288e"><pre>plt.plot(x, y) plt.title(<span class="hljs-string">'Sales Over Time'</span>) plt.xlim(<span class="hljs-number">0</span>, <span class="hljs-number">5</span>) plt.ylim(<span class="hljs-number">0</span>, <span class="hljs-number">40</span>) plt.show()</pre></div><p id="7995"><b>Output:</b></p><figure id="6304"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*jh8A97ibQ-kXDG5DGLF5MQ.png"><figcaption></figcaption></figure><p id="10ee"><code>plt.xlim()</code> and <code>plt.ylim()</code> allow you to set the minimum and maximum values for the axes.</p><h2 id="67db">Customizing Ticks and Tick Labels</h2><p id="6

Options

2ab">Ticks and tick labels can be customized to better represent your data:</p><div id="a20e"><pre>plt.plot(x, y) plt.title(<span class="hljs-string">'Sales Over Time'</span>) plt.xticks([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], [<span class="hljs-string">'Jan'</span>, <span class="hljs-string">'Feb'</span>, <span class="hljs-string">'Mar'</span>, <span class="hljs-string">'Apr'</span>]) plt.yticks([<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>], [<span class="hljs-string">'Low'</span>, <span class="hljs-string">'Medium'</span>, <span class="hljs-string">'High'</span>]) plt.show()</pre></div><p id="71b7">Output:</p><figure id="ff18"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*9Y0q5HFwLiOyVQU1y5ZoAA.png"><figcaption></figcaption></figure><p id="839c"><b>In this example:</b></p><ul><li><code>plt.xticks()</code> replaces the default numeric ticks with custom labels like 'Jan', 'Feb', etc.</li><li><code>plt.yticks()</code> customizes the y-axis ticks to display 'Low', 'Medium', and 'High'.</li></ul><h2 id="0e48">Adding Annotations</h2><p id="ce93">Annotations can highlight specific points or trends in your plot:</p><div id="d0db"><pre>plt.plot(x, y, marker=<span class="hljs-string">'o'</span>) plt.title(<span class="hljs-string">'Sales Over Time'</span>) plt.xlabel(<span class="hljs-string">'Time (months)'</span>) plt.ylabel(<span class="hljs-string">'Sales (units)'</span>) plt.annotate(<span class="hljs-string">'Peak Sales'</span>, xy=(<span class="hljs-number">4</span>, <span class="hljs-number">30</span>), xytext=(<span class="hljs-number">3</span>, <span class="hljs-number">35</span>), arrowprops=<span class="hljs-built_in">dict</span>(facecolor=<span class="hljs-string">'black'</span>, arrowstyle=<span class="hljs-string">'->'</span>)) plt.show()</pre></div><p id="112d"><b>Output:</b></p><figure id="ec0b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*dtIYsYLHcqRRrarLhtk2Kg.png"><figcaption></figcaption></figure><p id="8ac0">In this example:</p><ul><li><code>plt.annotate()</code> adds the text 'Peak Sales' near the point (4, 30).</li><li><code>xytext</code> sets the position of the annotation text.</li><li><code>arrowprops</code> adds an arrow pointing to the annotated point.</li></ul><h1 id="5d75">Conclusion</h1><p id="8819">In this second part of the “<b>Mastering Matplotlib</b>” series, we enhanced our plots by adding informative <b>titles, labels, and legends</b>. We also explored how to customize the plot’s appearance by adjusting dimensions, changing axis limits, customizing ticks, and adding annotations. These techniques are essential for creating clear, informative, and visually appealing plots.</p><p id="6d75">In the next part of the series (<a href="https://readmedium.com/mastering-matplotlib-3-exploring-different-plot-types-bd13d18ff613"><b>Part — 3</b></a>), we’ll delve deeper into different types of plots, such as bar plots, histograms, scatter plots, and pie charts, and explore how to create and customize them using Matplotlib.</p><p id="4f00"><b>If you like the article and would like to support me make sure to:</b></p><p id="f4db">👏 Clap for the story (<b>as much as you liked it <a href="https://emojipedia.org/smiling-face-with-smiling-eyes"></a></b><a href="https://emojipedia.org/smiling-face-with-smiling-eyes">😊</a>) and follow me 👉 📰 View more content on my medium profile 🔔 Follow Me: <a href="https://www.linkedin.com/in/ebimsv/"><b>LinkedIn</b></a> | <a href="https://medium.com/@ebimsv"><b>Medium</b></a> | <a href="https://github.com/Ebimsv?tab=repositories"><b>GitHub</b></a> | <a href="https://x.com/ebiimsv"><b>Twitter</b></a></p><p id="6bc0">Feel free to share your thoughts and questions in the comments below!</p><h1 id="0779">References:</h1></article></body>

Mastering Matplotlib: Part 2. Enhancing Plots with Labels, Titles, Legends, and Customizations

Elevate Your Data Visualization Skills with Essential Plot Components and Personalization Techniques

🔙 Previous: Introduction and Basic Plotting Techniques

🔜 Next: Exploring Different Plot Types

Note: You can find all the code examples for Matplotlib series in my GitHub repository.

Welcome back to the second part of the “Mastering Matplotlib” series. In the first part, we covered the basics of Matplotlib, including how to create simple line plots and customize them with different styles and markers. Now, we’re going to take your plotting skills to the next level by focusing on how to enhance your plots with labels, titles, legends, and various customization techniques.

1. Labels, Titles, and Legends

Adding Titles and Labels

Adding titles and labels is essential for making your plots informative and easy to understand. Let’s start by adding a title to the plot and labels to the x and y axes:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

plt.plot(x, y)
plt.title('Sales Over Time')
plt.xlabel('Time (months)')
plt.ylabel('Sales (units)')
plt.show()

Output:

In this example:

  • plt.title('Sales Over Time') adds a title to the plot.
  • plt.xlabel('Time (months)') labels the x-axis.
  • plt.ylabel('Sales (units)') labels the y-axis.

Customizing Fonts and Sizes

You can further customize the appearance of your titles and labels by adjusting their fonts and sizes:

plt.title('Sales Over Time', fontsize=16, fontweight='bold', color='blue')
plt.xlabel('Time (months)', fontsize=12, fontstyle='italic')
plt.ylabel('Sales (units)', fontsize=12, fontstyle='italic')
plt.plot(x, y)
plt.show()

Output:

Here:

  • fontsize adjusts the size of the text.
  • fontweight can make the text bold.
  • fontstyle can italicize the text.
  • color changes the text color.

Creating and Positioning Legends

Legends help distinguish between different data series in your plot. You can add a legend using the legend() function:

y2 = [15, 25, 20, 35]

plt.plot(x, y,  label='Product A')
plt.plot(x, y2, label='Product B')
plt.xlabel('Time (months)')
plt.ylabel('Sales (units)')
plt.title('Sales Comparison')
plt.legend(loc='upper left')
plt.show()

Output:

In this example:

  • label='Product A' and label='Product B' specify the labels for the two lines.
  • plt.legend(loc='upper left') positions the legend in the upper left corner of the plot.

You can position the legend using various options like 'upper right', 'lower left', 'center', or even by specifying coordinates.

Adding Gridlines

Gridlines make it easier to read values off the plot. You can add them with the grid() function:

plt.plot(x, y)
plt.xlabel('Time (months)')
plt.ylabel('Sales (units)')
plt.title('Sales Over Time')
plt.grid(True)
plt.show()

Output:

Setting plt.grid(True) turns on the gridlines, and you can further customize them by adjusting their style, color, and width:

plt.grid(color='gray', linestyle='--', linewidth=0.5)

Please try the above code and see the result of that.

2. Plot Customization

Customizing your plot’s dimensions, axes, ticks, and adding annotations can greatly enhance its readability and aesthetic appeal.

Adjusting Plot Dimensions

You can adjust the size of your plot using the figsize parameter in plt.figure():

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.title('Sales Over Time')
plt.show()

Output:

This example creates a plot that is 8 inches wide and 4 inches tall.

Changing Axes Limits

Sometimes, you might want to set specific limits for your x and y axes:

plt.plot(x, y)
plt.title('Sales Over Time')
plt.xlim(0, 5)
plt.ylim(0, 40)
plt.show()

Output:

plt.xlim() and plt.ylim() allow you to set the minimum and maximum values for the axes.

Customizing Ticks and Tick Labels

Ticks and tick labels can be customized to better represent your data:

plt.plot(x, y)
plt.title('Sales Over Time')
plt.xticks([1, 2, 3, 4], ['Jan', 'Feb', 'Mar', 'Apr'])
plt.yticks([10, 20, 30], ['Low', 'Medium', 'High'])
plt.show()

Output:

In this example:

  • plt.xticks() replaces the default numeric ticks with custom labels like 'Jan', 'Feb', etc.
  • plt.yticks() customizes the y-axis ticks to display 'Low', 'Medium', and 'High'.

Adding Annotations

Annotations can highlight specific points or trends in your plot:

plt.plot(x, y, marker='o')
plt.title('Sales Over Time')
plt.xlabel('Time (months)')
plt.ylabel('Sales (units)')
plt.annotate('Peak Sales', xy=(4, 30), xytext=(3, 35),
             arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.show()

Output:

In this example:

  • plt.annotate() adds the text 'Peak Sales' near the point (4, 30).
  • xytext sets the position of the annotation text.
  • arrowprops adds an arrow pointing to the annotated point.

Conclusion

In this second part of the “Mastering Matplotlib” series, we enhanced our plots by adding informative titles, labels, and legends. We also explored how to customize the plot’s appearance by adjusting dimensions, changing axis limits, customizing ticks, and adding annotations. These techniques are essential for creating clear, informative, and visually appealing plots.

In the next part of the series (Part — 3), we’ll delve deeper into different types of plots, such as bar plots, histograms, scatter plots, and pie charts, and explore how to create and customize them using Matplotlib.

If you like the article and would like to support me make sure to:

👏 Clap for the story (as much as you liked it 😊) and follow me 👉 📰 View more content on my medium profile 🔔 Follow Me: LinkedIn | Medium | GitHub | Twitter

Feel free to share your thoughts and questions in the comments below!

References:

Matplotlib
Python
Machine Learning
AI
Visualization
Recommended from ReadMedium