玫瑰图(Rose Diagram)是一种极坐标图表,通常用于表示数据的方向分布或周期性变化。例如,风向分布、活动频率等。
1. 数据准备
绘制玫瑰图需要以下数据:
- 方向角度:数据的方向(例如 0° 到 360°)。
- 频率或值:每个方向对应的强度或频率。
示例数据:
方向 (度) | 频率 |
---|---|
0 | 10 |
45 | 15 |
90 | 20 |
135 | 25 |
180 | 10 |
225 | 5 |
270 | 15 |
315 | 20 |
2. 使用 Python 绘制玫瑰图
2.1 使用 Matplotlib
安装 Matplotlib
如果未安装 Matplotlib,可以使用以下命令安装:
pip install matplotlib
示例代码
import numpy as np
import matplotlib.pyplot as plt
# 数据准备
angles = np.array([0, 45, 90, 135, 180, 225, 270, 315]) # 方向角度
values = np.array([10, 15, 20, 25, 10, 5, 15, 20]) # 对应频率
# 将角度转换为弧度
angles_rad = np.deg2rad(angles)
# 设置极坐标图
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': 'polar'})
bars = ax.bar(angles_rad, values, width=np.pi/4, edgecolor='black', align='center', color='skyblue')
# 图表美化
ax.set_theta_zero_location('N') # 设置北方为 0°
ax.set_theta_direction(-1) # 顺时针显示
ax.set_title("Rose Diagram Example", va='bottom')
# 显示图表
plt.show()
2.2 使用 Plotly
安装 Plotly
pip install plotly
示例代码
import plotly.graph_objects as go
# 数据准备
angles = [0, 45, 90, 135, 180, 225, 270, 315] # 方向角度
values = [10, 15, 20, 25, 10, 5, 15, 20] # 对应频率
# 绘制玫瑰图
fig = go.Figure(go.Barpolar(
r=values,
theta=angles,
width=[45] * len(angles), # 设置扇形宽度
marker_color=values,
marker_colorscale='Blues',
))
fig.update_layout(
title="Rose Diagram Example",
polar=dict(
angularaxis=dict(direction="clockwise"),
radialaxis=dict(gridcolor="lightgrey")
),
showlegend=False
)
fig.show()
2.3 使用 Seaborn(结合 Matplotlib)
安装 Seaborn
pip install seaborn
示例代码
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# 数据准备
angles = np.array([0, 45, 90, 135, 180, 225, 270, 315]) # 方向角度
values = np.array([10, 15, 20, 25, 10, 5, 15, 20]) # 对应频率
# 将角度转换为弧度
angles_rad = np.deg2rad(angles)
# 创建极坐标图
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, polar=True)
sns.barplot(x=angles_rad, y=values, ax=ax, palette="coolwarm", edgecolor="black")
# 图表美化
ax.set_theta_zero_location('N') # 设置北方为 0°
ax.set_theta_direction(-1) # 顺时针显示
ax.set_title("Rose Diagram with Seaborn", va='bottom')
plt.show()
3. 使用 R 绘制玫瑰图
安装所需包
install.packages("ggplot2")
示例代码
library(ggplot2)
# 数据准备
data <- data.frame(
direction = c(0, 45, 90, 135, 180, 225, 270, 315),
frequency = c(10, 15, 20, 25, 10, 5, 15, 20)
)
# 绘制玫瑰图
ggplot(data, aes(x = factor(direction), y = frequency, fill = frequency)) +
geom_bar(stat = "identity", width = 1) +
coord_polar(start = 0) +
scale_fill_gradient(low = "skyblue", high = "blue") +
labs(title = "Rose Diagram Example", x = "Direction", y = "Frequency") +
theme_minimal()
4. 优化玫瑰图
-
颜色渐变:
- 使用渐变色(如
coolwarm
或Blues
)表示强度,增强视觉效果。
- 使用渐变色(如
-
方向标注:
- 确保方向标注清晰(如设置北方为起点,顺时针或逆时针)。
-
网格线与刻度:
- 添加径向网格线和刻度线以便用户理解频率。
-
交互式图表:
- 使用 Plotly 或类似工具增强交互性,鼠标悬停时显示详细信息。
5. 应用场景
- 风向与风速分析:显示不同风向的风速分布。
- 周期性变化:分析一年中各月份的特定活动频率。
- 用户行为数据:展示用户访问时间的分布趋势。
- 地震学研究:表示地震波的传播方向。
6. 总结
玫瑰图是一种直观的极坐标图表,适用于表示方向性或周期性数据的分布。通过工具(如 Matplotlib、Plotly、R 的 ggplot2)绘制玫瑰图并进行优化,可以帮助用户更好地理解数据的方向和强度分布特点。