Master Matplotlib: Step-by-Step Guide to Plotting Line, Scatter, Bar, and More
This tutorial walks you through installing Matplotlib, importing it alongside NumPy, and creating a variety of common charts—including line, scatter, bar, histogram, pie, and box plots—detailing the required code, parameters, and customization options for each visualization.
To handle 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 via the command line on Windows (cmd) or macOS (Terminal) using:
<code>pip install matplotlib</code>If you are using Anaconda, the library is already installed. Typically we import its 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 rich scientific and statistical charts such as line, scatter, histogram, and more. 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 inline in Jupyter notebooks</code>Line Plot plot()
The plot function shows variable trends.
Method call: <code>plt.plot(x, y, ls='-', lw=2, label='plot figure')</code>
Parameters: x : values on the x‑axis y : values on the y‑axis ls : line style lw : line width label : legend label
<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.
Method call: <code>plt.scatter(x, y, c='b', label='scatter figure')</code>
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>Bar Plot bar()
The bar() function draws categorical data distributions on the x‑axis.
Method call: <code>plt.bar(x, y)</code>
Parameters: x : categorical positions on the x‑axis 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.
Method call: <code>plt.hist(x)</code>
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 percentage composition of categorical data.
Method call: <code>plt.pie(x)</code>
Parameters: x : percentages of each category explode : offset for highlighted slices label : slice 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 creates a box‑and‑whisker plot.
Method call: <code>plt.boxplot(x)</code>
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>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.