093、Python操作Excel生成统计图表

在Excel里做统计表是我们经常会做的一件事情。我们也可以通过编程的方式操作Excel生成统计图表。

下面是官方的一个很有参考价值的案例:

from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
from copy import deepcopy

wb = Workbook(write_only=True)
ws = wb.create_sheet()

rows = [
    ('Number', 'Batch 1', 'Batch 2'),
    (2, 10, 30),
    (3, 40, 60),
    (4, 50, 70),
    (5, 20, 10),
    (6, 10, 40),
    (7, 50, 30),
]


for row in rows:
    ws.append(row)


chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "Bar Chart"
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'

data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")

chart2 = deepcopy(chart1)
chart2.style = 11
chart2.type = "bar"
chart2.title = "Horizontal Bar Chart"

ws.add_chart(chart2, "G10")


chart3 = deepcopy
### Python 解析 Excel 文件并生成图表 为了实现这一目标,通常会使用 `pandas` 库来读取 Excel 文件中的数据,并利用 `matplotlib` 或者内置的 `pandas.plot()` 方法来进行可视化。以下是具体的操作方法: #### 导入必要的库 首先需要导入所需的库,包括 `pandas` 和 `matplotlib.pyplot`。 ```python import pandas as pd import matplotlib.pyplot as plt ``` #### 加载 Excel 数据 假设有一个名为 "airport_data.xlsx" 的 Excel 文件位于当前工作目录下,则可以通过如下方式加载该文件的数据帧对象。 ```python data_frame = pd.read_excel('airport_data.xlsx') print(data_frame.head()) # 查看前几行数据以便了解结构 ``` #### 绘制简单的折线图 如果想要基于某列数值创建一条时间序列曲线,比如按月份统计旅客吞吐量的变化趋势,那么可以直接调用 DataFrame 对象上的 plot 函数。 ```python plt.figure(figsize=(10,6)) data_frame.set_index('Month')['PassengerTraffic'].plot() plt.title('Monthly Passenger Traffic Trend') plt.xlabel('Month') plt.ylabel('Number of Passengers') plt.grid(True) plt.tight_layout() plt.show() ``` #### 创建柱状对比图 对于不同机场之间的年度总客流量比较而言,更适合采用条形图形式展现差异性;这里选取两个机场作为例子说明。 ```python comparison_df = data_frame[['AirportName','AnnualTotal']].groupby(['AirportName']).sum().reset_index() fig, ax = plt.subplots(figsize=(12,7)) bars = comparison_df.plot.bar(x='AirportName', y='AnnualTotal', legend=False, color=['skyblue'], ax=ax) for bar in bars.patches: height = bar.get_height() ax.annotate(f'{int(height)}', xy=(bar.get_x() + bar.get_width()/2., height), xytext=(0,3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') ax.set_title('Comparison Between Two Airports\' Annual Total Passenger Traffic') ax.set_xlabel('Airports') ax.set_ylabel('Total Number Of Passengers (Millions)') plt.xticks(rotation=45) plt.tight_layout() plt.show() ``` 以上代码片段展示了如何从 Excel 中提取数据并通过图形化的方式直观呈现出来[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿游也

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值