今天主要演示三种图表类型
1.柱形图
柱状图,是一种使用矩形条,对不同类别进行数值比较的统计图表。最基础的柱形图,需要一个分类变量和一个数值变量。在柱状图上,分类变量的每个实体都被表示为一个矩形(通俗讲即为“柱子”),而数值则决定了柱子的高度。
# 导入绘图库
import matplotlib.pyplot as plt
# 创建图形对象和坐标轴对象
fig, ax = plt.subplots()
# 定义水果名称(横坐标)
fruits = ['apple', 'blueberry', 'cherry', 'orange']
# 对应每种水果的数量(柱子的高度)
counts = [40, 100, 30, 55]
# 定义每个柱子的图例标签
# bar_labels = ['red', 'blue', '_red', 'orange'] # 颜色名
# bar_labels = ['red', 'blue', 'green', 'orange'] # 更标准写法
bar_labels = ['apple', 'blueberry', 'cherry', 'orange'] # 使用水果名作为图例标签
# 设置每个柱子的颜色,使用自定义的柔和十六进制颜色
# bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange'] # tab颜色
# bar_colors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange'] # 标准颜色
bar_colors = ['#FFB3BA', '#FFDFBA', '#FFFFBA', '#BAE1FF'] # 更柔和的渐变配色
# 画柱状图
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
# 设置纵轴标签
ax.set_ylabel('fruit supply')
# 设置横轴标签
ax.set_xlabel('fruits')
# 设置图表标题
ax.set_title('Fruit supply by kind and color')
# 添加图例
ax.legend(title='Fruit color')
# 显示图表
plt.show()
结果显示为选择水果名与更柔和的渐变配色,也可以选择另外的配色进行绘制,生成的柱形图也会有变化。
接下来在原本图表的基础上加上一条趋势线来展示不同水果供应数量的变化,代码如下
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['apple', 'blueberry', 'cherry', 'orange']
bar_colors = ['#FFB3BA', '#FFDFBA', '#FFFFBA', '#BAE1FF']
# 绘制条形图
# ax.bar(fruits, counts, label='Fruit Supply', color=bar_colors)
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
# 计算折线的数据点位置(每个条形的中心)
x_positions = range(len(fruits))
line_values = counts
# 绘制折线(可自定义)
ax.plot(x_positions, line_values, marker='o', linestyle='-', color='black', linewidth=2, label='Line')
# 设置坐标轴标签和标题
ax.set_ylabel('fruit supply')
ax.set_xlabel('fruits')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Legend')
plt.show()
显而易见的是,加上趋势线之后,变量之间的变化幅度变得更为直观,当然趋势线也可以进行自定义设置,如果觉得这条线太黑或是太粗,都可以进行调节,在绘制折线部分可以进行
再当然,这条折线能不能形状也能改变呢?可以的,本文通过代码示例来展示一个平滑曲线
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['apple', 'blueberry', 'cherry', 'orange']
bar_colors = ['#FFB3BA', '#FFDFBA', '#FFFFBA', '#BAE1FF']
# 绘制条形图
# ax.bar(fruits, counts, label='Fruit Supply', color=bar_colors)
ax.bar(fruits, counts, label=bar_labels, color=bar_colors)
# 计算折线的数据点位置(每个条形的中心)
x_positions = np.arange(len(fruits))
line_values = counts
# 使用样条插值生成平滑曲线
x_smooth = np.linspace(x_positions.min(), x_positions.max(), 3000)
spl = make_interp_spline(x_positions, line_values, k=3) # k=3 表示三次样条插值
y_smooth = spl(x_smooth)
# 绘制平滑折线
# ax.plot(x_smooth, y_smooth, marker='o', linestyle='-', color='blue', linewidth=1, label='Smooth Line')
ax.plot(x_smooth, y_smooth, linestyle='-', color='blue', linewidth=1, label='Smooth Line')
# 设置坐标轴标签和标题
ax.set_ylabel('fruit supply')
ax.set_xlabel('fruits')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Legend')
plt.xticks(x_positions, fruits) # 确保x轴标签与条形对齐
plt.show()
2.折线图
上文最后引进了趋势线,其实也就是折线图的基本样式。折线图是是一个由笛卡尔坐标系(直角坐标系),一些点和线组成的统计图表,常用来表示数值随连续时间间隔或有序类别的变化。
import matplotlib.pyplot as plt
# 数据
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
# 将水果名称转换为对应的 x 坐标
x = range(len(fruits)) # [0, 1, 2, 3]
# 绘制折线图
plt.plot(x, counts, marker='o', color='skyblue', label='Fruit Supply')
# 设置横坐标为水果名称
plt.xticks(x, fruits)
# 添加坐标轴标题和图表标题
plt.xlabel('Fruit')
plt.ylabel('Supply')
plt.title('Fruit Supply Line Chart')
# 添加图例
plt.legend()
# 显示图表
plt.show()
3.饼图
饼图,或称饼状图,是一个划分为几个扇形的圆形统计图表。在饼图中,每个扇形的弧长(以及圆心角和面积)大小,表示该种类占总体的比例,且这些扇形合在一起刚好是一个完全的圆形。其中,饼图最显著的功能在于表现“占比”。
import matplotlib.pyplot as plt # 导入绘图库
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' # 定义饼图的类别标签
sizes = [15, 30, 45, 10] # 定义每个类别所占的比例
fig, ax = plt.subplots() # 创建图形对象和坐标轴对象
explode = (0.1, 0.3, 0.1, 0.1) # 设置饼图“爆炸”效果,仅“爆炸”第二个扇区('Hogs')
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
colors=['#FFB3BA', '#FFDFBA', '#FFFFBA', '#BAE1FF'], pctdistance=1.1, labeldistance=0.6,
shadow=True, startangle=90, textprops={'size': 'larger'}, radius=1.2)
plt.show() # 显示绘制的图表
其中对一些参数进行说明:
ax.pie()
是用来绘制饼图的主要函数。它有许多参数,可以定制饼图的外观和行为:
-
sizes
:指定每个扇区的大小,即比例值。 -
explode
:设置饼图“爆炸”效果,突出显示某个扇区。 -
labels
:为每个扇区设置标签(在此为水果的名称)。 -
autopct='%1.1f%%'
:显示百分比,%1.1f%%
表示保留一位小数的百分比。 -
colors
:自定义每个扇区的颜色(通过十六进制色值)。 -
pctdistance=1.1
:百分比标签距离饼图中心的距离,设置得比较远。 -
labeldistance=0.6
:标签距离饼图中心的距离,设置得较近。 -
shadow=True
:添加阴影效果,使饼图看起来更立体。 -
startangle=90
:设置饼图的起始角度,90° 表示从顶部开始绘制。 -
textprops={'size': 'larger'}
:设置文本大小,使标签文字更大。 -
radius=1.2
:设置饼图的半径,1.2 比默认的更大。