4-02-3 Matplotlib 散点图、发散型条形图、饼图

本文探讨了数据可视化的重要原则,并列举了不同类型的图表,如散点图、发散条形图和饼图,用于展示数据的相互关系、偏差和组成元素。通过美国中西部各州的大专学历与贫穷线比例的散点图,揭示了教育水平与贫困的关系。接着,利用发散条形图展示了汽车油耗表现的差异。最后,用饼图分析了mtcars数据集中不同汽缸数汽车的占比,8缸车占比最高。这些图表有效地传达了复杂数据的特征和趋势。
摘要由CSDN通过智能技术生成

接下来要讨论的是在数据可视化的过程,我们希望透过图表来表达数据的特色,一个良好的图表应该具备以下特色:

  • 提供准确、有需求的信息,不歪曲事实。
  • 设计简单,获取时不会太费力。
  • 美感是为了支持这些信息,而不是为了掩盖这些信息;
  • 不要提供太过丰富的信息与太过复杂的结构。

图形可以分成以下的种类

  • 相互关系 (Correlation) :用来显示不同变量之间的相互关系,有以下这些图-散点图 (Scatter plot) 、带边界的气泡图 (Bubble plot with Encircling) 、带有最佳拟合线的散点图 (Scatter plot with line of best fit) 、抖动图分布散点图 (Jittering with stripplot) 、计数图 (Counts Plot) 、边缘直方图 (Marginal Histogram) 、边际箱线图 (Marginal Boxplot) 、相关图 (Correlogram) 、成对图 (Pairwise Plot)等。
  • 偏差 (Deviation):用来展现不同变量之间的差异性,常建的图形有发散型条形图 (Diverging Bars) 、发散型文本 (Diverging Texts) 、发散型点图 (Diverging Dot Plot) 、带标记的发散棒棒糖图 (Diverging Lollipop Chart with Markers) 、 面积图(Area Chart)等。
  • 等级 (Ranking):有效地表达了事物或物品的排列顺序,常见的是有序的条形图 (Ordered Bar Chart) 、棒棒糖图 (Lollipop Chart) 、散点图 (Dot Plot) 、斜线图 (Slope Chart) 、 哑铃图 (Dumbbell Plot)。
  • 分布 (Distribution):绘制概率与统计中的分布图,包括连续变量直方图 (Histogram for Continuous Variable) 、分类变量直方图 (Histogram for Categorical Variable) 、密度图 (Density Plot) 、直方图密度曲线 (Density Curves with Histogram) 、欢乐图 (Joy Plot) 、分布式点图 (Distributed Dot Plot) 、 箱线图 (Box Plot) 、点加方框图 (Dot + Box Plot) 、小提琴图 (Violin Plot) 、人口金字塔 (Population Pyramid) 、 分类图 (Categorical Plots) 等。
  • 组成元素 (Composition):用来表示成分的分布情形,包括华夫饼图表 (Waffle Chart) 、饼形图表 (Pie Chart) 、树形图 (Treemap) 、条形图 (Bar Chart) 等。
  • 变化 (Change):用来凸显时间或是空间的变化情形,包括时间序列图 (Time Series Plot) 、带波峰和波谷注释的时间序列 (Time Series with Peaks and Troughs Annotated) 、自相关图 (Autocorrelation Plot) 、互相关图 (Cross Correlation Plot) 、时间序列分解图 (Time Series Decomposition Plot) 、多重时间序列 (Multiple Time Series) 、使用次级 Y 轴绘制不同比例 (Plotting with different scales using secondary Y axis) 、带误差带的时间序列 (Time Series with Error Bands) 、堆叠面积图 (Stacked Area Chart) 、未堆叠的面积图 (Area Chart Unstacked) 、日历热图 (Calendar Heat Map) 、季节性图 (Seasonal Plot)等。
  • 分组 (Groups):区别不同的组别,包括系统树图 (Dendrogram) 、聚类图 (Cluster Plot) 、安德鲁斯曲线 (Andrews Curve) 、平行坐标 (Parallel Coordinates)。

相互关系-散点图 (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
  
midwest = 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数据处理-文章目录

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值