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


Plotting and Styling Individual Points with scatter()


Download 4.21 Mb.
Pdf ko'rish
bet253/344
Sana31.01.2024
Hajmi4.21 Mb.
#1818553
1   ...   249   250   251   252   253   254   255   256   ...   344
Bog'liq
Python Crash Course, 2nd Edition

Plotting and Styling Individual Points with scatter()
Sometimes, it’s useful to plot and style individual points based on certain 
characteristics. For example, you might plot small values in one color and 
larger values in a different color. You could also plot a large data set with 
mpl_squares.py


Generating Data
311
one set of styling options and then emphasize individual points by replot­
ting them with different options.
To plot a single point, use the 
scatter()
method. Pass the single (xy
values of the point of interest to 
scatter()
to plot those values:
import matplotlib.pyplot as plt
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(2, 4)
plt.show()
Let’s style the output to make it more interesting. We’ll add a title, label 
the axes, and make sure all the text is large enough to read:
import matplotlib.pyplot as plt
plt.style.use('seaborn')
fig, ax = plt.subplots()

ax.scatter(2, 4, s=200)
# Set chart title and label axes.
ax.set_title("Square Numbers", fontsize=24)
ax.set_xlabel("Value", fontsize=14)
ax.set_ylabel("Square of Value", fontsize=14)
# Set size of tick labels.
ax.tick_params(axis='both', which='major', labelsize=14)
plt.show()
At  we call 
scatter()
and use the 
s
argument to set the size of the dots 
used to draw the graph. When you run scatter_squares.py now, you should see 
a single point in the middle of the chart, as shown in Figure 15­5.
Figure 15-5: Plotting a single point
scatter_squares.py


312
Chapter 15
Plotting a Series of Points with scatter()
To plot a series of points, we can pass 
scatter()
separate lists of x­ and y­ 
values, like this:
import matplotlib.pyplot as plt
x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16, 25]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, s=100)
# Set chart title and label axes.
--snip--
The 
x_values
list contains the numbers to be squared, and 
y_values
con­
tains the square of each number. When these lists are passed to 
scatter()

Matplotlib reads one value from each list as it plots each point. The points 
to be plotted are (1, 1), (2, 4), (3, 9), (4, 16), and (5, 25); Figure 15­6 shows 
the result.
Figure 15-6: A scatter plot with multiple points

Download 4.21 Mb.

Do'stlaringiz bilan baham:
1   ...   249   250   251   252   253   254   255   256   ...   344




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