3.3.3 matplotlib库中pyplot模块里的主要作图函数
(1)scatter()函数画散点图
scatter()函数根据坐标画点,其语法格式如下:
matplotlib.pyplot.scatter(x, y, c=None, marker=None,linewidths=None)
其主要参数的意义如下:
X,y:此二参数确定画点的坐标位置;
C:此参数设置画点所采用的颜色,既可以是一个表示颜色的字符串 c=”红色”,也可以是十六进制表示的字符串c="#ff0000";
Marker:此参数表示画点所采用的形状,如点、星星、三角形等,典型设置如下:
marker | description |
"." | point |
"," | pixel |
"o" | circle |
"v" | triangle_down |
"^" | triangle_up |
"<" | triangle_left |
">" | triangle_right |
"s" | square |
"*" | star |
"H" | hexagon |
"+" | plus |
"D" | diamond |
"X" | x (filled) |
"8" | octagon |
linewidths:设置画点的宽度;
【医学案例3-4】某妇幼保健医院测得100名初生婴儿身长数据,采用散点图显示各位初生婴儿的身长数据。数据形式如表3-2所示(部分),该数据以excel表格的形式存储在当前目录中,文件名为"newbaby.xlsx”。
表3-2 部分初生婴儿身长数据
newBabyNo | newBabyHeight | gender |
1 | 48 | male |
2 | 48 | female |
3 | 47 | female |
4 | 42 | female |
5 | 53 | male |
…… | …… | …… |
97 | 51 | female |
98 | 45 | female |
99 | 52 | male |
100 | 54 | female |
【散点图的代码实例】
from matplotlib import pyplot as plt
from matplotlib import font_manager as ft
import pandas as pd
myFont = ft.FontProperties(fname='C:\Windows\Fonts\simsun.ttc')
excelFileName="newbaby.xlsx"
try:
newBaby = pd.DataFrame(pd.read_excel(excelFileName))
x=newBaby['newBabyNo']
y=newBaby['newBabyHeight']
# 默认情况下不能显示中文,fontproperties=myFont设置字体参数
plt.xlabel("婴儿编号",fontproperties=myFont)
plt.ylabel("婴儿身长",fontproperties=myFont)
plt.title("初生婴儿身长数据",fontproperties=myFont)
plt.xlim([0,100]) #横轴表示婴儿的编号
plt.ylim([0,70]) #纵轴表示婴儿的身长
#用散点图画出每个婴儿的身长数据,红色c="red"星号,marker="*",线宽为2
plt.scatter(x,y,c="red",marker="*",linewidths=2)
plt.show()
except FileNotFoundError:
print("打开文件出错!")
【运行效果】
图3-2 婴儿身长散点图