第三章 可视化数据
matplotlib~ mat(h)plot lib(rary) 数学 绘图 库
1. 绘图需要调用matplotlib包中的pylot模块:
from matplotlib import pyplot as mpl
2. 因为matplotlib.pyplot模块默认不显示中文,所以需要动态配置中文字体,可以调用matplotlib包的子包pylab:
import pylab as pla
pla.rcParams['font.sans-serif']=['simsun'] #字体缺失时 采用‘simsun’(宋体)字体,为系统自带字
#体类型,‘C:\Windows\Fonts’可查看有哪些字体
pla.rcParams['axes.unicode_minus'] = False #axes:坐标轴(复数),minus:负值,
#该语句使坐标轴可显示负数
一、条形图
1. mpl.bar() 为绘制条形图的函数:
第一个参数(一个序列)确定每个(bar)条的横坐标(横坐标默认居于条形中间),第二个参数(一个序列)确定每个条的高度(值),第三个参数可设定条形的宽度(宽度默认为0.8)
grades = [83,95,91,87,70,0,85,82,100,67,73,77,0]
decile = lambda grade: grade // 10 * 10
histogram = Counter(decile(grade) for grade in grades)
plt.bar([ x for x in histogram.keys()], histogram.values(),8)
2. mpl.axis()设置坐标轴的取值范围(显示范围);mpl.xticks();mpl.yticks()设置x和y坐标轴的刻度标记; mpl.xlabel(), mpl.ylabel() 设置x和y坐标轴的名称;mpl.title()设置整个图表的名称,mpl.show() 展示图表。
plt.axis([-5, 105, 0, 5]) # x轴取值从-5到105,y轴取值0到5,参数为一个序列
plt.xticks([10 * i for i in range(11)]) # x轴标记为0,10,...,100,参数为一个序列
plt.xlabel("十分相") #参数为一个字符串
plt.ylabel("学生数")
plt.title("考试分数分布图")
plt.show()
二、折线图
1. mpl.plot() 为绘制折线图的函数:
第一个参数(一个序列)确定折线图中每个点的横坐标,第二参数(一个序列)确定每个点的纵坐标,参数color确定颜色,参数marker确定每个点的标记形状,参数linestyle确定线条类型,参数label确定图例(legend)的名称。
plt.plot(years, gdp, color='green',
marker
='o',
linestyle
='solid')
variance = [1, 2, 4, 8, 16, 32, 64, 128, 256]
bias_squared = [256, 128, 64, 32, 16, 8, 4, 2, 1]
total_error = [x + y for x, y in zip(variance, bias_squared)]
xs = [i for i, _ in enumerate(variance)]
#多次调用plot可在一个图上显示多条折线
plt.plot(xs, variance, 'g-', label='variance') # 绿色实线 green
plt.plot(xs, bias_squared, 'r-.', label='bias^2') # 红色点虚线 red
plt.plot(xs, total_error, 'b:', label='total error') # 蓝色点线 blue
2. mpl.legend()函数确定图例的位置
plt.legend(loc=9) # loc=9指的是“顶部中央” ,不调用则没有图例,缺参则默认为顶部中央
3. 其他关于坐标轴的mpl.xlabel()等函数与条形图相同
三、散点图
1. mpl.scatter()为绘制散点图的函数:
第一个和第二个参数(序列)确定点的横坐标和纵坐标,
friends = [ 70, 65, 72, 63, 71, 64, 60, 64, 67]
minutes = [175, 170, 205, 120, 220, 130, 105, 145, 190]
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
plt.scatter(friends, minutes)
2. mpl.annotate()为每个点加标注
for label, friend_count, minute_count in zip(labels, friends, minutes):
plt.annotate(label, xy=(friend_count, minute_count), # 把标记放在对应的点上
xytext=(5, -5), # 但要有轻微偏离
textcoords='offset points') # 标注与对应点的坐标关系,不可缺少