Using Matplotlib with Jupyter Notebook (original) (raw)

**Jupyter Notebook is a free, open-source web app that lets you create and share documents with live code and visualizations. It is commonly used for tasks like cleaning and transforming data, doing statistical analysis, creating visualizations and machine learning.

**Matplotlib is a popular Python library for creating 2D plots. It is easy to use with data in arrays. To start, you just need to import the necessary tools, prepare your data and use the plot() function to create a plot. Once you're done, you can display the plot with the **show() function. Matplotlib is written in **Python and works with **NumPy, a library that helps with numerical math.

Installing Matplotlib

Using **pip

To install Matplotlib with pip, open a terminal window and type:

pip install matplotlib

Using **Anaconda Prompt

To install Matplotlib, open the Anaconda Prompt and type:

conda install matplotlib

Importing Matplotlib

Importing matplotlib in Jupyter Notebook is easy; you can use this command to do that:

import matplotlib

Using Matplotlib with Jupyter Notebook

After the installation is completed. Let's start using Matplotlib with Jupyter Notebook. We will be plotting various graphs in the Jupyter Notebook using Matplotlib, such as:

Line Plot

Python `

from matplotlib import pyplot as plt

x = [5, 2, 9, 4, 7] y = [10, 5, 8, 4, 2]

plt.plot(x, y) plt.show()

`

**Output:

line-chart-matplotlib

Line Plot

**Bar Plot

Python `

from matplotlib import pyplot as plt

x = ['A', 'B', 'C', 'D', 'E'] y = [10, 5, 8, 4, 2]

plt.bar(x, y) plt.show()

`

**Output:

bar-chart-matplotlib

Bar Plot

Histogram

Python `

from matplotlib import pyplot as plt

data = [5, 2, 9, 4, 7, 1, 6, 8, 3, 7, 6, 4, 8, 5, 9]

plt.hist(data, bins=5, edgecolor='black') plt.show()

`

**Output:

histogram

Histogram

Scatter Plot

Python `

from matplotlib import pyplot as plt

x = [5, 2, 9, 4, 7] y = [10, 5, 8, 4, 2]

plt.scatter(x, y) plt.show()

`

**Output:

scatter-plot-matplotlib

Scatter Plot

Adding Title and Labeling the Axes in the graph

We can add title to the graph by using the following command

matplotlib.pyplot.title("My title")

We can label the x-axis and y-axis by using the following functions

matplotlib.pyplot.xlabel("Label for X-Axis")

matplotlib.pyplot.ylabel("Label for Y-Axis")

**Example:

Python `

from matplotlib import pyplot as plt

x = [5, 2, 9, 4, 7] y = [10, 5, 8, 4, 2]

Create scatter plot

plt.scatter(x, y)

plt.title("Position vs Time") plt.xlabel("Time (hr)") plt.ylabel("Position (Km)")

plt.show()

`