1、螺旋图适合用来显示大型时间内的数据趋势,也能有效地显示其周期性。较长的时间序列显得过于拥挤,通过螺旋图能更好的抓住眼球,但是不易读。
基本的螺旋框架
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# 设置随机种子
np.random.seed(0)
# 创建日期范围(5年数据)
dates = pd.date_range(start='1/1/2015', end='31/12/2019')
# 自定义销售数据,并归一化
sales = np.sin(np.linspace(0, 4*np.pi, len(dates))) + 10 + np.random.normal(0, 1, len(dates))
sales = (sales - np.min(sales)) / np.ptp(sales)
# 计算每个数据点所对应的半径和角度
# 半径等于天数除以一年的天数(这里用365做简化计算)
radius = np.linspace(0, len(sales) / 365, len(sales))
# 角度等于通过取余数将天数限制在365以内,然后转换为弧度
theta = (dates.dayofyear.values % 365) / 365 * 2 * np.pi
# 初始化布局
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection='polar')
ax.plot(theta, radius)
plt.show()
2、在螺旋方向上添加条形图
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# 设置随机种子
np.random.seed(0)
# 创建日期范围(5年数据)
dates = pd.date_range(start='1/1/2015', end='31/12/2019')
# 自定义销售数据,并归一化
sales = np.sin(np.linspace(0, 4*np.pi, len(dates))) + 10 + np.random.normal(0, 1, len(dates))
sales = (sales - np.min(sales)) / np.ptp(sales)
# 计算每个数据点所对应的半径和角度
# 半径等于天数除以一年的天数(这里用365做简化计算)
radius = np.linspace(0, len(sales) / 365, len(sales))
# 角度等于通过取余数将天数限制在365以内,然后转换为弧度
theta = (dates.dayofyear.values % 365) / 365 * 2 * np.pi
# 初始化布局
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, polar=True)
# 添加条形图数据
ax.bar(theta, sales, width=0.01, bottom=radius, color='r', alpha=0.5)
plt.show()
3、自定义螺旋图:半径、方向、颜色、边框网格等
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# 设置随机种子
np.random.seed(0)
# 创建日期范围(5年数据)
dates = pd.date_range(start='1/1/2015', end='31/12/2019')
# 自定义销售数据,并归一化
sales = np.sin(np.linspace(0, 4*np.pi, len(dates))) + 10 + np.random.normal(0, 1, len(dates))
sales = (sales - np.min(sales)) / np.ptp(sales)
# 计算每个数据点所对应的半径和角度
# 半径等于天数除以一年的天数(这里用365做简化计算),并将半径扩大两倍
radius = 2 * np.linspace(0, len(sales) / 365, len(sales))
# 角度等于通过取余数将天数限制在365以内,然后转换为弧度
theta = (dates.dayofyear.values % 365) / 365 * 2 * np.pi
# 初始化布局
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, polar=True)
# 设置极坐标的起始位置(从90度位置开始)和旋转方向为顺时针
ax.set_theta_offset(np.pi / 2)
ax.set_theta_direction(-1)
# 选择颜色
colors = ['b', 'g', 'r', 'c', 'm']
for year in range(2015, 2020):
# 寻找该年份的数据
indices = (pd.Series(dates).dt.year == year)
# 添加条形图数据,为每年选择不同的颜色
ax.bar(theta[indices], sales[indices], width=0.01, bottom=radius[indices],
color=colors[year-2015], alpha=0.5)
# 隐藏坐标轴和刻度
ax.set_yticklabels([])
ax.set_xticklabels([])
# 关闭极坐标网格线
ax.grid(False)
# 删除极坐标的外环(边框)
ax.spines['polar'].set_visible(False)
plt.show()
4、总结
以上基于matplotlib极坐标叠加条形图绘制出了螺旋图。
共勉~