接下来要讨论的是在数据可视化的过程,我们希望透过图表来表达数据的特色,一个良好的图表应该具备以下特色:
图形可以分成以下的种类
相互关系-散点图 (Scatter plot)
以下使用美国中西部各州 (midwest.csv) 的人口分布案例来观察,首先先依州来分群,共 16 的类别 (category),给每个类别不同的颜色,显示 midwild 这个数据集的信息,共有 437 笔数据, 28 个栏位,接着以位于贫穷线以下的比例 (percbelowpoverty, percent below poverty) 与大专生的比例 (percollege, Percent college educated) 来画出散点图,很明显的,大多数的点都是集中在左下角,大专学历的比例增加,则贫穷线下的比例就比较少,说明高中学历与贫穷的相关性。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/midwest.csv")
# 显示数据集信息,共有 437 笔数据, 28 个栏位
midwest.info()
# 对每一州指定一个颜色
states = np.unique(midwest['state'])
colors = [plt.cm.tab10(i/float(len(states)-1)) for i in range(len(states))]
# 指定画布大小
plt.figure(figsize=(16, 10), dpi= 80, facecolor='w', edgecolor='k')
# 画出每一州的散点图
for i, state in enumerate(states):
plt.scatter('percollege', 'percbelowpoverty', data=midwest.loc[midwest.state==state, :], s=20, color=colors[i], label=str(state))
# 指定坐标轴长度、X/Y 标签
plt.gca().set(xlim=(0, 60), ylim=(0, 60), xlabel='大专学历比例', ylabel='贫穷线以下比例')
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.title("美国中西部各州的大专学历比与贫穷线以下比例的散点图", fontsize=22)
plt.legend(fontsize=12)
plt.show()
图 4-2-5 大专教育程度与贫穷线以下的散点图
偏差-发散型条形图 (Diverging Bars)
如果您想要看到项目是如何基于单一的指标变化的,并且可视化这个变化的顺序和数量,发散条是一个很好的工具。它有助于快速区分数据中组的性能,非常直观,并能立即传达出要点。以下以 mtcars 这个数据集来观察,这些数据是从美国 1974 年的《汽车趋势》杂志中提取的,包括 32 辆汽车的燃料消耗和 14 个方面的汽车设计和性能,要观察的性能指标是每加仑可以开几英里的油耗表现 (miles per gallon),可以看出 Ferrari Dino 的油耗表现是居中, Toyota Corolla 的油耗表现最好, Lincoln Continental 最耗油。
mtcars 数据集说明
栏位 | 说明 |
---|---|
mpg | 每加仑开几英里 |
cyl | 汽缸数目 |
disp | 排气量 (以立方英吋为单位) |
hp | 总马力 |
drat | 后轴比 |
wt | 重量 (1000 lbs) |
qsec | 乘以 1/4 英里或 400 米 |
vs | 引擎类型 (0 = V-shaped, 1 = straight) |
am | 变速器 (0 = automatic, 1 = manual) |
gear | 前进齿轮数 |
carb | 化油器的数量 |
cars | 汽车型号 |
carname | 汽车型号 |
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")
df.info()
x = df.loc[:, ['mpg']]
df['mpg_z'] = (x - x.mean())/x.std()
df['colors'] = ['red' if x < 0 else 'green' for x in df['mpg_z']]
df.sort_values('mpg_z', inplace=True)
df.reset_index(inplace=True)
# Draw plot
plt.figure(figsize=(14,10), dpi= 80)
plt.hlines(y=df.index, xmin=0, xmax=df.mpg_z, color=df.colors, alpha=0.4, linewidth=5)
# Decorations
plt.gca().set(ylabel='$Model$', xlabel='$Mileage$')
plt.yticks(df.index, df.cars, fontsize=12)
plt.title('Diverging Bars of Car Mileage', fontdict={'size':20})
plt.grid(linestyle='--', alpha=0.5)
plt.show()
输出结果如下:
RangeIndex: 32 entries, 0 to 31
Data columns (total 14 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 mpg 32 non-null float64
1 cyl 32 non-null int64
2 disp 32 non-null float64
3 hp 32 non-null int64
4 drat 32 non-null float64
5 wt 32 non-null float64
6 qsec 32 non-null float64
7 vs 32 non-null int64
8 am 32 non-null int64
9 gear 32 non-null int64
10 carb 32 non-null int64
11 fast 32 non-null int64
12 cars 32 non-null object
13 carname 32 non-null object
dtypes: float64(5), int64(7), object(2)
memory usage: 3.6+ KB
图 4-2-6 汽车油耗表现的发散条状图
组成元素-饼形图表 (Pie Chart)
饼形图表是显示组成元素的经典方法,一般使用如果使用饼状图,强烈建议明确写下饼状图每个部分的百分比或数字。以下以 mtcars 的数据集,根据汽缸数来观察,发现 8 气缸的汽车种类最多,共有 14 量,占全部车的 43.8 %。
import pandas as pd
import matplotlib.pyplot as plt
df_raw = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")
# Prepare Data
df = df_raw.groupby('cyl').size().reset_index(name='counts')
# Draw Plot
fig, ax = plt.subplots(figsize=(12, 7), subplot_kw=dict(aspect="equal"), dpi= 80)
data = df['counts']
categories = df['cyl']
explode = [0,0.1,0]
def func(pct, allvals):
absolute = int(pct/100.*np.sum(allvals))
return "{:.1f}% ({:d} )".format(pct, absolute)
wedges, texts, autotexts = ax.pie(data,
autopct=lambda pct: func(pct, data),
textprops=dict(color="w"),
colors=plt.cm.Dark2.colors,
startangle=140,
explode=explode)
# Decoration
ax.legend(wedges, categories, title="汽缸数", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))
plt.setp(autotexts, size=10, weight=700)
ax.set_title("汽车汽缸数的饼图")
plt.show()
图 4-2-7 画出不同汽缸数汽车占比的饼图
Python数据处理-文章目录