玩命加载中...
# 内地城市排行(Python雷达图教程)
雷达图(Radar Chart)又被叫做蜘蛛网图,适用于显示有三个或更多的数值维度的对象。
本教程中,我们利用Matplotlib实现了雷达图,以及多个对象的比较。
数据使用了华顿研究院2018年8月发布的“中国内地百强城市”,并且利用雷达图进行展示。
预计学习用时:15分钟。
本教程基于**Python 3.5**。
原创者:**SofaSofa TeamM** | 修改校对:SofaSofa TeamC |
----
引入使用的模块
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
```
**数据下载点击[这里](http://sofasofa.io/tutorials/radar_plot/cities_ranking.csv)**(数据版权归华顿研究院所有)。
利用pandas读取数据
```python
data = pd.read_csv('cities_ranking.csv')
data.head()
```
|
排名 |
城市 |
总分 |
经济产值 |
财富储蓄 |
环境 |
科教 |
文化 |
卫生 |
0 |
1 |
北京 |
93.74 |
86.98 |
100.00 |
95.88 |
100.00 |
98.05 |
82.62 |
1 |
2 |
上海 |
88.23 |
88.96 |
90.81 |
76.25 |
90.25 |
100.00 |
75.72 |
2 |
3 |
广州 |
83.40 |
83.73 |
81.67 |
78.86 |
97.46 |
88.96 |
72.84 |
3 |
4 |
深圳 |
75.10 |
86.63 |
73.22 |
84.76 |
43.97 |
94.77 |
45.73 |
4 |
5 |
杭州 |
73.42 |
68.23 |
69.47 |
79.27 |
79.50 |
89.47 |
74.98 |
定义雷达图函数
```python
def plot_radar(data, city):
'''
data是上面读入的原始数据
city是要显示的城市,可以是一个城市,比如city="上海"
也可以是一组城市,比如city=["杭州", "南京"]
为了视觉效果,最多同时展示5个城市。
'''
if type(city) != list: city = [city]
# 从下面六项指标,体现城市发展水平
cols = ['文化', '科教', '经济产值', '财富储蓄', '环境', '卫生']
# 每个城市的配色
colors = ['green', 'blue', 'red', 'yellow', 'black']
# 把圆形进行六等分
angles = np.linspace(0.1 * np.pi, 2.1 * np.pi, len(cols), endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
# 初始化一个极坐标图像
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, polar=True)
# 逐一添加每个城市图像以及排名信息
for i, c in enumerate(city):
rank = data.loc[data['城市'] == c, '排名'].values[0]
stats = data.loc[data['城市'] == c, cols].values[0].tolist()
stats = np.concatenate((stats, [stats[0]]))
ax.plot(angles, stats, '-', linewidth=6, c=colors[i], label='%s 排名第%s'%(c, rank))
ax.fill(angles, stats, c=colors[i], alpha=0.25)
# 添加图例
ax.legend(loc=[0.25, 1.15], fontsize=18)
ax.set_yticklabels([])
ax.set_thetagrids(angles * 180/np.pi, cols, fontsize=16)
ax.grid(True)
# 完成
plt.show()
return fig
```
调用函数,试试看!先看看上海!
```python
plot_radar(data, "上海");
```

随机显示两座城市
```python
all_cities = data['城市'].tolist()
for city in np.random.choice(all_cities, 2):
plot_radar(data, city);
```


上面提到了,`plot_radar`可以对比多个城市。我们挑选几组,看看有没有你们的家乡哦!
```python
plot_radar(data, ['北京', '上海']);
plot_radar(data, ['广州', '深圳']);
plot_radar(data, ['杭州', '南京']);
plot_radar(data, ['成都', '重庆']);
plot_radar(data, ['苏州', '无锡']);
plot_radar(data, ['天津', '沈阳']);
plot_radar(data, ['武汉', '长沙']);
plot_radar(data, ['郑州', '西安']);
plot_radar(data, ['大连', '青岛']);
plot_radar(data, ['宁波', '南通']);
plot_radar(data, ['合肥', '南昌']);
```










