H a n d s o n, p r o j e c t b a s e d


Download 4.21 Mb.
Pdf ko'rish
bet250/344
Sana31.01.2024
Hajmi4.21 Mb.
#1818553
1   ...   246   247   248   249   250   251   252   253   ...   344
Bog'liq
Python Crash Course, 2nd Edition

Installing Matplotlib
To use Matplotlib for your initial set of visualizations, you’ll need to install 
it using 
pip
, a module that downloads and installs Python packages. Enter 
the following command at a terminal prompt:
python -m pip install --user matplotlib
This command tells Python to run the 
pip
module and install the 
matplotlib
package to the current user’s Python installation. If you use a 
command other than 
python
on your system to run programs or start a ter­
minal session, such as 
python3
, your command will look like this:
python3 -m pip install --user matplotlib
n o t e
 
If this command doesn’t work on macOS, try running the command again without 
the 
--user
 flag.
To see the kinds of visualizations you can make with Matplotlib, visit 
the sample gallery at https://matplotlib.org/gallery/. When you click a visual­
ization in the gallery, you’ll see the code used to generate the plot.
Plotting a Simple Line Graph
Let’s plot a simple line graph using Matplotlib, and then customize it to 
create a more informative data visualization. We’ll use the square number 
sequence 1, 4, 9, 16, 25 as the data for the graph. 
Just provide Matplotlib with the numbers, as shown here, and Matplotlib 
should do the rest:
import matplotlib.pyplot as plt
squares = [1, 4, 9, 16, 25]
mpl_squares.py


Generating Data
307

fig, ax = plt.subplots()
ax.plot(squares)
plt.show()
We first import the 
pyplot
module using the alias 
plt
so we don’t have to 
type 
pyplot
repeatedly. (You’ll see this convention often in online examples, 
so we’ll do the same here.) The 
pyplot
module contains a number of func­
tions that generate charts and plots.
We create a list called 
squares
to hold the data that we’ll plot. Then we 
follow another common Matplotlib convention by calling the 
subplots()
function . This function can generate one or more plots in the same fig­
ure. The variable 
fig
represents the entire figure or collection of plots that 
are generated. The variable 
ax
represents a single plot in the figure and is 
the variable we’ll use most of the time.
We then use the 
plot()
method, which will try to plot the data it’s given 
in a meaningful way. The function 
plt.show()
opens Matplotlib’s viewer and 
displays the plot, as shown in Figure 15­1. The viewer allows you to zoom 
and navigate the plot, and when you click the disk icon, you can save any 
plot images you like.
Figure 15-1: One of the simplest plots you can make in Matplotlib

Download 4.21 Mb.

Do'stlaringiz bilan baham:
1   ...   246   247   248   249   250   251   252   253   ...   344




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling