Master Matplotlib: Plot Lines, Scatter, Bars, Histograms, Pie & Box Plots
This tutorial demonstrates how to install and import Matplotlib, then provides detailed Python code examples for creating common chart types—including line, scatter, bars, histograms, pie & box plots—using NumPy data, with explanations of key parameters and visual customization options.
To process data and create visualizations, we first import the third‑party packages NumPy and the fast plotting module pyplot.
Installation and Import of Matplotlib
You can install Matplotlib from the command line (cmd on Windows or Terminal on macOS) with:
<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 the pyplot module and alias it as plt :
<code>import matplotlib.pyplot as plt</code>When plotting, we often combine Matplotlib with NumPy.
Common Plot Types
Matplotlib can draw a rich set of scientific and statistical charts such as line plots, scatter plots, histograms, etc. First import the libraries and prepare the data.
<code>import numpy as np # import NumPy
import matplotlib.pyplot as plt # import pyplot module
%matplotlib inline # display plots directly in Jupyter Notebook</code>Line Plot plot()
The plot function shows variable trends.
Calling 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 : text label for the plot
<code>x = np.linspace(0, 2, 100) # generate 100 points from 0 to 2
y = x**2 # quadratic function
y2 = x**0.5 # square‑root function
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.
Calling 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 : legend label 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>Resulting image:
Bar Chart bar()
The bar() function draws the distribution of categorical data on the x‑axis.
Calling method: plt.bar(x, y)
Parameters: x : categories on the x‑axis y : count 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>Resulting image:
Histogram hist()
The hist() function draws the distribution of quantitative data on the x‑axis.
Calling method: plt.hist(x)
Parameters: x : data to plot on the x‑axis bins : number of bins color : bar color rwidth : relative bar width alpha : transparency
<code>x = np.random.randint(0, 10, 100) # 100 random integers between 0 and 9
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>Resulting image:
Pie Chart pie()
A pie chart shows the percentage of each category in qualitative data.
Calling method: plt.pie(x)
Parameters: x : percentages of each category explode : offset for highlighted slices labels : category labels autopct : format for displayed percentages 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>Resulting image:
Box Plot boxplot()
The boxplot function creates a box‑and‑whisker plot.
Calling method: plt.boxplot(x)
Parameters: x : input data for the box plot
<code>x = np.random.normal(0, 1, 1000) # generate normal distribution data
plt.boxplot(x)
plt.xlabel('A')
plt.ylabel('Y')
plt.grid(linestyle='--', alpha=0.3)
plt.title('Boxplot')
plt.savefig('images/mat0106.png')
</code>Resulting image:
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".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.