Fundamentals 9 min read

Master Matplotlib: Install, Import, and Create Common Plots in Python

This guide walks you through installing Matplotlib, importing it with NumPy, and using its pyplot interface to create line, scatter, bar, histogram, pie, and box plots, complete with code examples and visual results for effective data visualization.

Model Perspective
Model Perspective
Model Perspective
Master Matplotlib: Install, Import, and Create Common Plots in Python

To handle data and plotting, we first import the third‑party packages NumPy and the fast plotting module pyplot.

Matplotlib Installation and Import

We can install Matplotlib via the command line using:

<code>pip install matplotlib</code>

If you are using Anaconda, the library is already installed and does not need to be reinstalled. Typically we import its pyplot module and alias it as plt .

<code>import matplotlib.pyplot as plt</code>

When plotting we often combine NumPy as well.

Common Plot Types

Matplotlib can draw a rich set of scientific and statistical graphs such as line charts, scatter plots, histograms, etc. First import the libraries and prepare the data.

<code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline</code>

Line Plot plot()

The plot function shows variable trends.

Call method: plt.plot(x, y, ls='-', lw=2, label='plot figure')

Parameters: x : values on the x‑axis y : values on the y‑axis ls : line style lw : line width label : label text for the plot

<code>x = np.linspace(0, 2, 100)
 y = x**2  # quadratic
 y2 = x*0.5  # root
 plt.plot(x, y, 'c', ls='-', lw=3, label='Square')
 plt.plot(x, y2, 'b', ls='-', lw=3, label='Root')
 plt.legend()
 plt.xlabel('X')
 plt.ylabel('Y')
 plt.title('Plot')
 plt.savefig('images/mat0101.png')
</code>

Resulting image:

Scatter Plot scatter()

Scatter plots help discover relationships between variables.

Call method: plt.scatter(x, y, c='b', label='scatter figure')

Parameters: x : values on the x‑axis y : values on the y‑axis c : marker color label : label text s : marker size cmap : color map

<code>x = np.linspace(0.05, 10, 100)
 y = np.random.rand(100)
 y1 = np.random.rand(100)
 plt.scatter(x, y, c='b', label='Scatter 1')
 plt.scatter(x, y1, c='r', label='Scatter 2')
 plt.legend()
 plt.grid()
 plt.title('Scatter')
 plt.savefig('images/mat0102.png')
</code>

Bar Chart bar()

The bar() function draws categorical distributions along the x‑axis.

Call method: plt.bar(x, y)

Parameters: x : categorical positions y : counts for each category

<code>x = [1,2,3,4,5,6,7,8]
 y = [3,1,4,5,8,9,7,2]
 plt.bar(x, y, align='center', color='k', tick_label=list('ABCDEFGH'))
 plt.xlabel('X')
 plt.ylabel('Y')
 plt.grid(axis='y')
 plt.title('Bar')
 plt.savefig('images/mat0103.png')
</code>

Histogram hist()

The hist() function visualizes the distribution of quantitative data on the x‑axis.

Call method: plt.hist(x)

Parameters: x : data to plot bins : number of bins color : bar color rwidth : bar width ratio alpha : transparency

<code>x = np.random.randint(0, 10, 100)
 bins = range(0, 10, 1)
 plt.hist(x, bins=bins, color='c', rwidth=0.8, alpha=0.5)
 plt.xlabel('X')
 plt.ylabel('Y')
 plt.title('Histogram')
 plt.savefig('images/mat0104.png')
</code>

Pie Chart pie()

The pie() function shows percentages of qualitative categories.

Call method: plt.pie(x)

Parameters: x : percentages of each category explode : offset for highlighted slices labels : category labels autopct : format for percentage display colors : slice colors

<code>nums = [0.05, 0.45, 0.15, 0.35]
 kinds = ['A','B','C','D']
 colors = ["C1","C2","C3","C4"]
 plt.figure(figsize=(8,8))
 plt.pie(nums, explode=[0.05,0,0,0], labels=kinds, autopct="%3.1f%%", colors=colors)
 plt.title('Pie')
 plt.savefig('images/mat0105.png')
</code>

Box Plot boxplot()

The boxplot function draws a box‑and‑whisker plot.

Call method: plt.boxplot(x)

Parameters: x : input data for the box plot

<code>x = np.random.normal(0, 1, 1000)
 plt.boxplot(x)
 plt.xlabel('A')
 plt.ylabel('Y')
 plt.grid(linestyle='--', alpha=0.3)
 plt.title('Boxplot')
 plt.savefig('images/mat0106.png')
</code>
Pythondata-visualizationMatplotlibNumPyPlottingScatter PlotLine Plot
Model Perspective
Written by

Model Perspective

Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.