Matplotlib中如何绘制饼图和柱状图
时间: 2023-12-04 08:15:50 浏览: 107
要绘制饼图和柱状图,需要使用Matplotlib库。以下是绘制饼图和柱状图的代码示例:
绘制饼图:
```python
import matplotlib.pyplot as plt
# 数据
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
# 绘图
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
ax.axis('equal')
# 显示图形
plt.show()
```
这段代码会绘制一个简单的饼图,其中“labels”是每个部分的标签,“sizes”是每个部分的大小。
绘制柱状图:
```python
import matplotlib.pyplot as plt
# 数据
labels = ['A', 'B', 'C', 'D']
values = [15, 30, 45, 10]
# 绘图
fig, ax = plt.subplots()
ax.bar(labels, values)
# 显示图形
plt.show()
```
这段代码会绘制一个简单的柱状图,其中“labels”是每个柱子的标签,“values”是每个柱子的高度。
相关问题
利用matplotlib和pandas绘制有柱状图、折线图和饼图构成的组合图
好的,以下是一个简单的例子,展示如何利用matplotlib和pandas绘制有柱状图、折线图和饼图构成的组合图:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 创建数据
data = {'apple': [3, 2, 4, 5], 'orange': [1, 5, 2, 6], 'banana': [2, 3, 1, 4]}
df = pd.DataFrame(data, index=['Jan', 'Feb', 'Mar', 'Apr'])
# 创建子图
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))
# 绘制柱状图
df.plot(kind='bar', ax=axs[0])
axs[0].set_title('Fruit sales')
# 绘制折线图
df.plot(kind='line', ax=axs[1])
axs[1].set_title('Fruit sales')
# 绘制饼图
plt.figure(figsize=(5,5))
df.sum().plot(kind='pie', autopct='%1.1f%%')
plt.title('Fruit sales')
# 显示图形
plt.show()
```
在这个例子中,我们创建了一个包含水果销售数据的DataFrame对象,并利用matplotlib的子图功能,在一个Figure对象中绘制了柱状图、折线图和饼图。其中,柱状图和折线图绘制在一个子图中,饼图绘制在另一个子图中。最后,我们调用show()函数显示图形。
需要注意的是,这只是一个简单的例子,实际的数据可能更加复杂,需要更多的数据处理和绘图技巧。但是,这个例子可以作为一个起点,帮助你开始利用matplotlib和pandas绘制组合图。
2.读取“成绩.xlsx”文件,执行以下操作: (1)使用matplotlib库绘制柱状图对比不同性别总评成绩的平均分; (2)将总评成绩按分数段划分成分数等级(优、良、中、及格、不及格),根据分布状况分组统计人数,使用matplotlib库绘制饼图。
要在Python中完成这个任务,你需要先安装必要的库,如pandas用于数据处理,matplotlib用于绘图,以及openpyxl或xlrd用于读取Excel文件。以下是实现这两个步骤的示例代码:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 1. 读取Excel文件
# 这里假设文件路径为'scores.xlsx'
data = pd.read_excel('成绩.xlsx')
# 确保文件存在,检查列名,如果需要的话
if '性别' and '总评成绩' not in data.columns:
print("文件中缺少必要的列,请检查并确认")
# (1)绘制柱状图
gender_scores = data.groupby('性别')['总评成绩'].mean()
plt.bar(gender_scores.index, gender_scores)
plt.xlabel('性别')
plt.ylabel('平均分')
plt.title('不同性别总评成绩平均值对比')
plt.show()
# (2)分数段划分和统计
score_bins = [0, 60, 75, 85, 90] # 分数段,可根据实际调整
grade_distribution = pd.cut(data['总评成绩'], score_bins, labels=['不及格', '及格', '良好', '优秀'])
grades_counts = grade_distribution.value_counts(normalize=True) * 100 # 将百分比转换为数值
# 绘制饼图
plt.pie(grades_counts, labels=grades_counts.index, autopct='%1.1f%%')
plt.title('总评成绩分数等级分布')
plt.ylabel('')
plt.show()
```
阅读全文
相关推荐















