标签:Python与Excel,pandas
在上篇文章中,我们简要地讨论了如何使用web数据在Python中创建一个图形,但是如果我们所能做的只是在Python中显示一个绘制的图形,那么它就没有那么大的用处了。假如用户不知道如何运行Python并重新这个绘制图形呢?解决方案是使用Excel作为显示结果的媒介,因为大多数人的电脑上都安装有Excel。因此,我们只需将Python生成的图形保存到Excel文件中,并将电子表格发送给用户。
根据前面用Python绘制图形的示例(参见:在Python中绘图),在本文中,我们将:
1)美化这个图形,
2)将其保存到Excel文件中。
美化图表
之前我们生成的这个图,尽管对于2行代码来说并不太糟糕,但该图与专业级图相差甚远,所以让我们使它更漂亮。
图1
我们将使用matplotlib修改绘图格式。由于这不是本文的主题,所以不会详细介绍下面的代码。后续文章中会有讲解。
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import (
FormatStrFormatter,
AutoMinorLocator,
FuncFormatter,
)
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
df =pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')
df = df.iloc[:,4:]
global_num = df.sum()
fig, ax = plt.subplots()
ax.set(title = 'Global CovidConfirmed Cases',
xlabel = 'Time',
ylabel = 'Number of cases')
ax.yaxis.set_major_formatter(FuncFormatter(lambdax, p: format(x/1000000) +'M'))
date_form = DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(date_form)
locator = mdates.DayLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=3))
ax.yaxis.grid()
dates = pd.to_datetime(global_num.index)
plt.plot(dates, global_num)
plt.show()
图2
将Python生成的图形保存到Excel文件中
我们需要先把图形保存到电脑里。
plt.savefig(r'D:\python_pretty_plot.png')
然后可以使用xlsxwriter库创建一个Excel文件。要将确认病例数据保存到Excel中,执行以下操作:
writer = pd.ExcelWriter(r'D:\Python_plot.xlsx',engine = 'xlsxwriter')
global_num.to_excel(writer,sheet_name='Sheet1')
然后,将图像添加到该工作表:
worksheet = writer.sheets['Sheet1']
worksheet.insert_image('C2','D:\python_pretty_plot.png')
writer.save()
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有