python dataframe某列数据要做成柱形图 自定义柱形图每个柱子的统计范围,每个柱子范围不一样,画布大小自定义,添加数据标签
时间: 2023-12-10 10:42:41 浏览: 75
首先,我们需要安装matplotlib库和pandas库,可以通过以下命令进行安装:
```
pip install matplotlib pandas
```
接下来,我们可以使用pandas库读取数据,然后使用matplotlib库绘制柱形图。假设我们的数据如下:
```python
import pandas as pd
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
'score': [80, 90, 75, 85, 95]
}
df = pd.DataFrame(data)
```
现在,我们想要绘制score列的柱形图,每个柱子的统计范围不同。假设我们要绘制的柱子分别为[0, 60], [60, 70], [70, 80], [80, 90], [90, 100],我们可以使用matplotlib库的hist函数进行绘制:
```python
import matplotlib.pyplot as plt
# 柱子的边界
bins = [0, 60, 70, 80, 90, 100]
# 绘制柱形图
plt.hist(df['score'], bins=bins)
# 设置画布大小
plt.figure(figsize=(8, 6))
# 添加数据标签
for i in range(len(bins) - 1):
plt.text((bins[i] + bins[i+1]) / 2, df['score'][(df['score'] >= bins[i]) & (df['score'] < bins[i+1])].count() + 1, str(df['score'][(df['score'] >= bins[i]) & (df['score'] < bins[i+1])].count()), ha='center')
# 显示图形
plt.show()
```
这样就可以绘制出柱子范围不同、画布大小自定义、带有数据标签的柱形图了。
阅读全文
相关推荐













