用Python绘制高颜值环形玫瑰图
在日常的数据分析工作中,如何将枯燥的数据转化为直观易懂的图表是一项重要技能。今天我们就来学习如何使用Python中的Matplotlib库,绘制一个既美观又专业的环形玫瑰图,来展示水果销售情况。
效果预览
首先来看一下最终效果:一个色彩鲜明、标签清晰、带有图例的环形玫瑰图,不仅直观展示了各种水果的销售数量,还具有很高的视觉吸引力。
准备工作
在开始之前,我们需要导入必要的库并设置中文字体支持:
1 2 3 4 5 6 7
| import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Patch
plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False
|
数据准备
我们使用8种常见水果的销售数据:
1 2 3
| categories = ['苹果', '香蕉', '橙子', '葡萄', '草莓', '西瓜', '菠萝', '芒果'] values = [25, 18, 15, 12, 10, 8, 7, 5] colors = ['#FF6B6B', '#FFD166', '#06D6A0', '#118AB2', '#073B4C', '#EF476F', '#F78C6B', '#7DDF64']
|
创建极坐标图
玫瑰图是基于极坐标系的,我们需要创建一个极坐标轴:
1
| fig, ax = plt.subplots(figsize=(10, 8), subplot_kw=dict(projection='polar'))
|
计算角度和宽度
为了在图表中添加间隔,我们需要计算每个扇形的角度和宽度:
1 2 3
| N = len(values) theta = np.linspace(0, 2*np.pi, N, endpoint=False) width = 2 * np.pi / N * 0.7
|
绘制环形玫瑰图
通过设置内半径来实现环形效果:
1 2 3
| inner_radius = 5 bars = ax.bar(theta, values, width=width, bottom=inner_radius, color=colors, edgecolor='white', linewidth=1.5, alpha=0.8)
|
添加标签和标题
1 2 3 4 5 6
| ax.set_xticks(theta) ax.set_xticklabels(categories, fontsize=10)
plt.title('水果销售情况环形玫瑰图', fontsize=16, pad=20)
|
添加数值标签
在每个扇形的中间位置显示具体数值:
1 2 3 4 5 6
| for bar, value in zip(bars, values): height = bar.get_height() mid_radius = inner_radius + height/2 angle = bar.get_x() + bar.get_width()/2 ax.text(angle, mid_radius, f'{value}', ha='center', va='center', fontsize=10, color='white', weight='bold')
|
美化图表
移除不必要的网格线和边框,使图表更加简洁:
1 2 3 4 5 6 7 8 9 10
| ax.set_ylim(0, inner_radius + max(values) + 5)
ax.set_yticks([]) ax.grid(False)
ax.spines['polar'].set_visible(False) ax.set_frame_on(False)
|
添加图例
创建自定义图例,让读者能够清晰地理解每个颜色代表的含义:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| legend_elements = [Patch(facecolor=color, edgecolor='white', label=f'{cat}: {val}', alpha=0.8) for color, cat, val in zip(colors, categories, values)]
legend = ax.legend(handles=legend_elements, loc='upper left', bbox_to_anchor=(0.02, 0.98), title='水果销售数量', title_fontsize=12, fontsize=10, frameon=True, fancybox=True, shadow=True, framealpha=0.95, edgecolor='gray', facecolor='#f8f9fa')
legend.get_title().set_fontweight('bold')
|
显示图形
1 2
| plt.tight_layout() plt.show()
|
总结
通过这个教程,我们学会了如何使用Matplotlib创建环形玫瑰图。这种图表特别适合展示周期性或分类数据,比传统的饼图或条形图更加吸引眼球。
关键技巧包括:
- 使用极坐标系
- 设置内半径创建环形效果
- 保留适当间隔提高可读性
- 添加清晰的数值标签
- 使用美观的配色方案
- 添加信息丰富的图例
你可以根据需要调整颜色、大小、间隔等参数,创建符合自己需求的玫瑰图。希望这个教程对你有帮助!
尝试一下:修改代码中的水果种类和销售数据,为你自己的数据创建个性化的环形玫瑰图吧!