(5) 统计北京各区的站点分布情况,用柱形图显示
时间: 2024-03-24 19:41:51 浏览: 13
要统计北京各区的站点分布情况并用柱形图显示,可以按照以下步骤进行:
1. 首先,导入必要的库,包括pandas和matplotlib。
```python
import pandas as pd
import matplotlib.pyplot as plt
```
2. 使用pandas库中的read_csv()函数读取包含站点信息的CSV文件。假设该CSV文件名为“stations.csv”。
```python
df = pd.read_csv('stations.csv')
```
3. 对站点进行分组统计,使用pandas库中的groupby()和size()函数。假设该数据集中包含“district”列,表示站点所属的区域。
```python
df_grouped = df.groupby('district').size()
```
4. 使用matplotlib库中的bar()函数绘制柱形图。
```python
plt.bar(df_grouped.index, df_grouped.values)
plt.title('Station Distribution in Beijing')
plt.xlabel('District')
plt.ylabel('Number of Stations')
plt.show()
```
上述代码中,plt.bar()函数的第一个参数传入各区名称的列表(即df_grouped.index),第二个参数传入各区站点数的列表(即df_grouped.values)。接下来,使用plt.title()、plt.xlabel()和plt.ylabel()函数分别设置图表标题、X轴标签和Y轴标签。最后,使用plt.show()函数显示柱形图。
完整代码示例:
```python
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('stations.csv')
df_grouped = df.groupby('district').size()
plt.bar(df_grouped.index, df_grouped.values)
plt.title('Station Distribution in Beijing')
plt.xlabel('District')
plt.ylabel('Number of Stations')
plt.show()
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)