题目来源于帮助学妹做的大作业(貌似文科好一些也学Python?)
有关信息取自自国家卫生健康委员会官方网站公开的数据,真实可靠。数据仅用于学习之用!
思路:selenium模拟浏览器,进入每天的详情页,正则匹配提取时间和累计报告接种新冠病毒疫苗剂次,翻页爬取,保存数据。要控制访问频率,不然可能就返回空白了。
Excel可视化疫苗接种情况,主要就是:选中这两列数据—插入—选择全部图表—插入折线图—选中折线可以添加趋势线,然后就是各种坐标轴、刻度、填充、线条、效果的精修,得到如下所示效果:
当时大作业要求:(最早起始于2021-03-24,请开发爬虫程序,将数据更新到10.31日),现在更新到了最新的2022/1/30(写这篇文章时)。Excel懒得再调了,这下直接用 Python 可视化。
df = pd.read_excel("到20220129.xlsx")
df
# x轴:时间顺序 y轴:疫苗接种数目(万剂次)
x_data = [i for i in range(1, len(df) + 1)]
y_data = [i for i in df["疫苗接种数目(万剂次)"]][::-1]
# 用5次多项式拟合 调用poly1d方法得到多项式系数
y_fit = polyfit(x_data, y_data, 5)
print('y_fit:', y_fit)
y_fit_1d = np.poly1d(y_fit)
print('y_fit_1d:\n', y_fit_1d)
y_hat = np.polyval(y_fit, x_data)
# This function is also OK: y_hat = y_fit_1d(x)
print('y_hat:', y_hat)
# 计算相关系数和R方
print('Correlation coefficients:')
print(np.corrcoef(y_hat, y_data))
correlation = np.corrcoef(y_hat, y_data)[0, 1]
R_squre = correlation ** 2
print("R_squre:", R_squre)
formula = r'$\mathcal{R}^2 = ' + '%.6f$' % R_squre
xtick = np.linspace(min(x_data), max(x_data), 1000)
# matplotlib其实是不支持显示中文的 显示中文需要一行代码设置字体
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei'] # 显示中文
plt.rcParams['axes.unicode_minus'] = False # 显示负号
fig, ax = plt.subplots(figsize=(6, 4), dpi=500)
# 折线图
plt.scatter(x_data, y_data,
color="b")
# 拟合的多项式曲线
plt.plot(xtick, y_fit_1d(xtick), "r-",
lw=2, label=formula)
# x y 轴标签 标题 字体设置
plt.xlabel("时间顺序",
fontdict={"size": 14, "weight": "bold", "color": "black"})
plt.ylabel("疫苗接种数目(万剂次)",
fontdict={"size": 14, "weight": "bold", "color": "black"}
)
# 设置坐标轴刻度标签的大小
plt.tick_params(axis='x', direction='out',
labelsize=12, length=3.6)
plt.tick_params(axis='y', direction='out',
labelsize=12, length=3.6)
print(":".join(["CSDN叶庭云", "https://yetingyun.blog.csdn.net/"]))
# 设置刻度值范围
ax.set_ylim(bottom=0, top=350000.0000001)
ax.set_yticks(np.arange(0, 350000.0000001, step=50000))
# 刻度数值用Times New Roman字体
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]
[label.set_color('black') for label in labels]
plt.grid(alpha=0.36, ls=":")
# 图例和网格的透明度设置
plt.legend(fontsize=14, frameon=False)
# 保存图片 展示show
plt.savefig("疫苗接种随时间变化情况可视化", dpi=500)
plt.show()
结果如下:
“我们相信中国,相信世界,有这么多人一起在努力,我们度过这个寒冬,明年的春节将不再那么寒冷。”
接下来就是新年啦,祝大家新年快乐,平安喜乐,万事如意!!
"""
@Author :叶庭云
@CSDN :https://yetingyun.blog.csdn.net/
"""