Adventures in Machine Learning

Mastering Matplotlib: Pie Charts and Stacked Bar Charts

Creating data visualizations like graphs, charts, and plots are a powerful way to showcase patterns, relationships, and correlations within data. Whether you’re a data scientist, analyst, or a student trying to represent data for a project or presentation, Matplotlib is a Python plotting library that can help you generate high-quality visualizations with ease.

In this article, we will explore two essential functionalities in Matplotlib: removing a legend from a plot and creating a stacked bar chart. We’ll start by discussing why it’s necessary to remove legends from plots and then proceed with the basic syntax and examples.

We’ll then move on to creating a basic stacked bar chart and look at ways to customize it further. Removing a Legend from a Plot in Matplotlib:

Legends are essential in data visualizations because they help decipher the information presented.

However, there may be cases where the legend is not required or might clutter the plot. In such instances, it is best to remove the legend altogether.

The basic syntax for removing legend in Matplotlib is as follows:

“`python

# Importing matplotlib

import matplotlib.pyplot as plt

# Plotting a line graph

plt.plot(x,y)

# Removing the legend

plt.legend().remove()

# Displaying the plot

plt.show()

“`

In the code snippet above, we first import the Matplotlib library and plot the line graph using `plt.plot()`. We then use `plt.legend().remove()` to remove the legend from the plot.

Finally, we display the plot using `plt.show()`. Let’s look at an example of how to remove the legend from a stacked bar chart that uses Pandas DataFrame:

“`python

# Importing necessary libraries

import pandas as pd

import matplotlib.pyplot as plt

# Creating sample data

df = pd.DataFrame({‘Apples’:[20,10,30,25], ‘Oranges’:[35,40,25,20]}, index=[‘Q1’, ‘Q2’, ‘Q3’, ‘Q4’])

# Creating a stacked bar chart

ax = df.plot(kind=’bar’, stacked=True)

# Removing legend

ax.get_legend().remove()

# Displaying the plot

plt.show()

“`

In the code snippet above, we first import the Pandas and Matplotlib libraries and create a sample dataframe using Pandas. We then create a stacked bar chart using `df.plot(kind=’bar’, stacked=True)`.

Finally, we remove the legend using `ax.get_legend().remove()` and display the plot using `plt.show()`. Creating a Stacked Bar Chart in Matplotlib:

A stacked bar chart is a type of chart that represents data in a vertical bar format, where each category’s data is represented by a vertical bar consisting of two or more segments that have different heights or lengths.

Let’s look at the basic code for creating a stacked bar chart using Matplotlib:

“`python

# Importing necessary libraries

import numpy as np

import matplotlib.pyplot as plt

# Creating sample data

data = np.array([[10, 30, 20, 25], [20, 20, 25, 15]])

# Creating a stacked bar chart

plt.bar(np.arange(4), data[0], label=’Category 1′)

plt.bar(np.arange(4), data[1], bottom=data[0], label=’Category 2′)

plt.xticks(np.arange(4), [‘A’, ‘B’, ‘C’, ‘D’])

# Adding the legend and title

plt.legend()

plt.title(‘Stacked Bar Chart’)

# Displaying the plot

plt.show()

“`

In the code snippet above, we first import the necessary libraries (NumPy and Matplotlib), create sample data using NumPy’s `np.array()`, and then create a stacked bar chart using `plt.bar()`. We set `bottom` to the first category to ensure that the bars stack on top of each other.

We set `xticks` and add a legend and title using `plt.legend()` and `plt.title()`, respectively. Finally, we display the plot using `plt.show()`.

We can also create a stacked bar chart using Pandas DataFrame. Let’s look at the code for the same:

“`python

# Importing necessary libraries

import pandas as pd

import matplotlib.pyplot as plt

# Creating sample data

df = pd.DataFrame({‘Apples’:[20,10,30,25], ‘Oranges’:[35,40,25,20]}, index=[‘Q1’, ‘Q2’, ‘Q3’, ‘Q4’])

# Creating a stacked bar chart

ax = df.plot(kind=’bar’, stacked=True)

# Customizing the chart

ax.set_xticklabels(df.index, rotation=0)

ax.set_title(‘Stacked Bar Chart’)

# Displaying the plot

plt.show()

“`

In the code snippet above, we first import the necessary libraries (Pandas and Matplotlib), create sample data using Pandas, and create a stacked bar chart using `df.plot(kind=’bar’, stacked=True)`. We then customize the chart using `ax.set_xticklabels(df.index, rotation=0)` and `ax.set_title(‘Stacked Bar Chart’)` and display the plot using `plt.show()`.

Conclusion:

In this article, we explored two essential functionalities of Matplotlib, i.e., removing a legend from a plot and creating a stacked bar chart. We discussed the importance of removing the legend from plots and provided code snippets with examples to explain the basic syntax and functions.

We also delved into creating a stacked bar chart with both NumPy arrays and Pandas DataFrames, along with customization options. With this article’s help, you can now create effective data visualizations using Matplotlib.

Creating data visualizations is an essential part of working with data it helps us to understand the insights that data holds. One of the most widely used and popular visualizations is a pie chart.

It is easy to understand, visually appealing, and effectively presents the distribution of data. Matplotlib is a Python library that provides numerous functionalities to create professional-looking data visualizations.

In this article, we will learn how to create a pie chart using Matplotlib and remove the legend from it. Creating a Pie Chart in Matplotlib:

Pie charts are commonly used to represent the proportion of each category in a dataset.

Let’s look at the basic code for creating a pie chart in Matplotlib:

“`python

# Importing necessary libraries

import matplotlib.pyplot as plt

# Creating data

labels = [‘Category 1’, ‘Category 2’, ‘Category 3’, ‘Category 4’]

sizes = [20, 30, 15, 35]

# Creating a pie chart

plt.pie(sizes, labels=labels)

# Displaying the plot

plt.show()

“`

In the code snippet above, we first import the Matplotlib library and create data for the pie chart. We then create a pie chart using `plt.pie()` and pass the `sizes` and `labels` as arguments.

Finally, we display the plot using `plt.show()`. Customizing the Pie Chart:

Now that we have created a basic pie chart, let’s learn how to modify it to make it visually appealing.

Here’s the code snippet to customize the pie chart:

“`python

# Importing necessary libraries

import matplotlib.pyplot as plt

# Creating data

labels = [‘Category 1’, ‘Category 2’, ‘Category 3’, ‘Category 4’]

sizes = [20, 30, 15, 35]

colors = [‘red’, ‘blue’, ‘green’, ‘yellow’]

# Creating a pie chart

plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct=’%1.1f%%’)

# Adding title

plt.title(‘Distribution of Categories’)

# Displaying the plot

plt.show()

“`

In the code snippet above, we have added the `colors` argument to pass a list of colors to be used for each category. We also use `startangle` to rotate the pie chart by 90 degrees.

`autopct` is used to display the percentage of each category on the chart. Finally, we add a title using `plt.title()`.

Removing Legend from a Pie Chart:

While legends can be incredibly helpful to understand data, they are not always necessary and can cause clutter in the visualization. In such cases, it might be best to remove the legend from the chart.

Here’s the code snippet to remove the legend from a pie chart:

“`python

# Importing necessary libraries

import matplotlib.pyplot as plt

# Creating data

labels = [‘Category 1’, ‘Category 2’, ‘Category 3’, ‘Category 4’]

sizes = [20, 30, 15, 35]

colors = [‘red’, ‘blue’, ‘green’, ‘yellow’]

# Creating a pie chart

plt.pie(sizes, labels=labels, colors=colors, startangle=90, autopct=’%1.1f%%’)

# Removing legend

plt.legend().remove()

# Displaying the plot

plt.show()

“`

In the code snippet above, we first create a pie chart using `plt.pie()` and pass the necessary arguments. Finally, we remove the legend using the `plt.legend().remove()` and display the plot using `plt.show()`.

Conclusion:

In this article, we have learned how to create a pie chart in Matplotlib and customize it to make it visually appealing. We also explored how to remove the legend from the pie chart for instances where it is not required.

Pie charts are a go-to choice when you want to represent the distribution of data. By customizing your pie chart, you can make it visually appealing and understandable.

With these skills, you can create an effective and compelling data visualization in Python. In this article, we explored the essential functionalities of Matplotlib by learning how to create a Pie Chart and a Stacked Bar Chart.

We learned to remove legends from plots to declutter the visualizations and customized them to make them visually appealing. Matplotlib provides a vast range of tools to create professional-looking data visualizations that can help us gain insights into data.

By learning these skills, we can effectively represent data and convey our findings to our audience. The takeaway from this article is that the basic syntax for creating Pie Chart and Stacked Bar Chart in Matplotlib is easy to learn, and customization adds a visually appealing touch to the visualizations.

By implementing these techniques, we can confidently create data visualizations for our projects, reports, and presentations.

Popular Posts