pandas绘制条形图及帕累托图
时间: 2023-10-10 15:06:12 浏览: 145
条形图是一种常用的可视化方法,用于比较不同类别下的数值数据。帕累托图是一种特殊的条形图,用于显示按照重要性排序的因素的贡献程度。
在pandas中,可以使用plot.bar()方法来绘制条形图,使用plot.barh()方法来绘制水平条形图。而绘制帕累托图则需要按照重要性排序后计算累计贡献率,并使用plot.bar()方法绘制两个数据系列,一个是原始数据的条形图,一个是累计贡献率的线图。
下面是一个简单的例子,演示如何使用pandas绘制条形图及帕累托图。
首先,我们需要导入必要的库并生成一些示例数据。
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 生成示例数据
np.random.seed(123)
data = pd.DataFrame({'A': np.random.randint(1, 10, 5),
'B': np.random.randint(1, 10, 5),
'C': np.random.randint(1, 10, 5)})
data.index = ['a', 'b', 'c', 'd', 'e']
print(data)
```
输出结果如下:
```
A B C
a 3 3 3
b 3 7 2
c 7 2 4
d 2 4 7
e 4 6 2
```
接下来,我们可以使用plot.bar()方法绘制条形图。
```python
data.plot.bar()
plt.show()
```
运行结果如下:
![条形图](https://cdn.jsdelivr.net/gh/datalaoshi/images/pandas-bar-chart.png)
我们也可以使用plot.barh()方法绘制水平条形图。
```python
data.plot.barh()
plt.show()
```
运行结果如下:
![水平条形图](https://cdn.jsdelivr.net/gh/datalaoshi/images/pandas-horizontal-bar-chart.png)
接下来,我们可以按照某一列数据的大小排序,计算每个类别的累计贡献率,并绘制帕累托图。
```python
# 按照列B的大小排序
sorted_data = data.sort_values('B', ascending=False)
# 计算每个类别的累计贡献率
cumulative = sorted_data.sum().cumsum() / sorted_data.sum().sum()
# 绘制帕累托图
fig, ax1 = plt.subplots()
ax1.bar(sorted_data.columns, sorted_data.sum())
ax1.tick_params(axis='y', labelcolor='tab:blue')
ax1.set_ylabel('Frequency', color='tab:blue')
ax2 = ax1.twinx()
ax2.plot(sorted_data.columns, cumulative, color='tab:red', marker='o')
ax2.tick_params(axis='y', labelcolor='tab:red')
ax2.set_ylabel('Cumulative Contribution', color='tab:red')
plt.show()
```
运行结果如下:
![帕累托图](https://cdn.jsdelivr.net/gh/datalaoshi/images/pandas-pareto-chart.png)
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)