Python数据分析(二)
(一)制作散点图
散点图运用的是motplotlib库里的pyplot模块的scatter方法
题目:绘制北京地区3月和10月日均气温变化散点图,数据如下:
a = [11, 17, 16, 11, 12, 11, 12, 6, 6, 7, 8, 9, 12, 15, 14, 17, 18, 21, 16, 17, 20, 14, 15, 15, 15, 19, 21, 22, 22, 22, 23]
b = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20, 21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11, 13, 12, 13, 6]
(a为3月份气温数据,b为10月份气温数据)
与绘制折线图的方法大同小异,只是绘制折线图用的是plt.plot,而绘制散点图用plt.scatter.
代码如下:
'''绘制散点图'''
from matplotlib import pyplot as plt
from matplotlib import font_manager
#导入字体
My_font = font_manager.FontProperties(fname=r'./shuxing.TTF')
#数据
y_3 = [11, 17, 16, 11, 12, 11, 12, 6, 6, 7, 8, 9, 12, 15, 14, 17, 18, 21, 16, 17, 20, 14, 15, 15, 15, 19, 21, 22, 22, 22, 23]
y_10 = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20, 21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11, 13, 12, 13, 6]
x_3 = range(1, 32)
x_10 = range(51, 82)
#修改图片大小和分辨率
plt.figure(figsize=(20, 8), dpi=80)
#修改x,y刻度
x = list(x_3)+list(x_10)
_xtick_label = ['3月{}日'.format(i) for i in x_3]
_xtick_label += ['10月{}日'.format(i-50) for i in x_10]
plt.xticks(x[::3], _xtick_label[::3], fontproperties=My_font, rotation=45)
plt.yticks(range(2, 30, 2))
#添加标签
plt.title('北京3月10月气温变化散点图', fontproperties=My_font, size=20, color='b')
plt.xlabel('时间', fontproperties=My_font)
plt.ylabel('气温', fontproperties=My_font)
plt.scatter(x_3, y_3, label='3月份', color='b')
plt.scatter(x_10, y_10, label='10月份', color='orange')
plt.legend(prop=My_font)
plt.grid(alpha=0.4)
#保存展示图片
plt.savefig(r"./d2.png")
plt.show()
图片展示:

通过散点图我们可以看出,3月份时间与气温成正比关系,10月份时间与气温成反比关系。(这也符合我们的常理)
结论:
散点图用于研究事物的分布规律、变化趋势,展示离群点。
本文通过使用Python的matplotlib库,展示了北京3月和10月日均气温变化的散点图,分析了气温随时间的变化趋势,揭示了气温与时间的关系。
1168

被折叠的 条评论
为什么被折叠?



