Python常见图表生成代码示例
引言
本文档整理了使用Python生成各类常见图表的代码示例,包括条形图、折线图、饼图等。所有代码均基于Matplotlib和Seaborn库实现,确保简洁易懂且可直接运行。
环境准备
首先需要安装必要的库:
1
| pip install matplotlib seaborn numpy pandas
|
一、条形图 (Bar Chart)
条形图适用于比较不同类别的数据值。
1.1 基本垂直条形图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import matplotlib.pyplot as plt import numpy as np
categories = ['A', 'B', 'C', 'D', 'E'] values = np.array([35, 25, 40, 30, 45])
plt.figure(figsize=(10, 6)) bars = plt.bar(categories, values, color='skyblue')
plt.title('基本垂直条形图', fontsize=15) plt.xlabel('类别', fontsize=12) plt.ylabel('数值', fontsize=12) plt.grid(axis='y', linestyle='--', alpha=0.7)
for bar in bars: height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2., height, f'{height}', ha='center', va='bottom')
plt.show()
|
中文不显示补充以下代码
1 2 3
| plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False
|
1.2 水平条形图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import matplotlib.pyplot as plt import numpy as np
categories = ['A', 'B', 'C', 'D', 'E'] values = np.array([35, 25, 40, 30, 45])
plt.figure(figsize=(10, 6)) bars = plt.barh(categories, values, color='lightgreen')
plt.title('水平条形图', fontsize=15) plt.xlabel('数值', fontsize=12) plt.ylabel('类别', fontsize=12) plt.grid(axis='x', linestyle='--', alpha=0.7)
for bar in bars: width = bar.get_width() plt.text(width, bar.get_y() + bar.get_height()/2., f'{width}', ha='left', va='center')
plt.show()
|
1.3 分组条形图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import matplotlib.pyplot as plt import numpy as np
categories = ['A', 'B', 'C', 'D', 'E'] values1 = np.array([35, 25, 40, 30, 45]) values2 = np.array([25, 35, 30, 45, 35])
bar_width = 0.35 index = np.arange(len(categories))
plt.figure(figsize=(12, 6)) bars1 = plt.bar(index, values1, bar_width, label='组1', color='skyblue') bars2 = plt.bar(index + bar_width, values2, bar_width, label='组2', color='lightgreen')
plt.title('分组条形图', fontsize=15) plt.xlabel('类别', fontsize=12) plt.ylabel('数值', fontsize=12) plt.xticks(index + bar_width/2, categories) plt.legend() plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
|
二、折线图 (Line Chart)
折线图适用于展示数据随时间或有序类别变化的趋势。
2.1 基本折线图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import matplotlib.pyplot as plt import numpy as np
x = np.linspace(0, 10, 100) y = np.sin(x)
plt.figure(figsize=(12, 6)) plt.plot(x, y, color='blue', linewidth=2, linestyle='-')
plt.title('基本折线图', fontsize=15) plt.xlabel('X轴', fontsize=12) plt.ylabel('Y轴', fontsize=12) plt.grid(linestyle='--', alpha=0.7) plt.axhline(0, color='black', linewidth=0.5) plt.axvline(0, color='black', linewidth=0.5)
plt.show()
|
2.2 多条折线图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import matplotlib.pyplot as plt import numpy as np
x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) y3 = np.sin(x) + np.cos(x)
plt.figure(figsize=(12, 6)) plt.plot(x, y1, label='sin(x)', color='blue', linewidth=2) plt.plot(x, y2, label='cos(x)', color='red', linewidth=2, linestyle='--') plt.plot(x, y3, label='sin(x)+cos(x)', color='green', linewidth=2, linestyle='-.')
plt.title('多条折线图', fontsize=15) plt.xlabel('X轴', fontsize=12) plt.ylabel('Y轴', fontsize=12) plt.legend(fontsize=10) plt.grid(linestyle='--', alpha=0.7)
plt.show()
|
2.3 带标记点的折线图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import matplotlib.pyplot as plt import numpy as np
x = np.arange(1, 11) y = np.array([12, 15, 13, 17, 19, 21, 18, 23, 25, 22])
plt.figure(figsize=(12, 6)) plt.plot(x, y, color='purple', linewidth=2, marker='o', markersize=8, markerfacecolor='white', markeredgewidth=2)
plt.title('带标记点的折线图', fontsize=15) plt.xlabel('时间', fontsize=12) plt.ylabel('数值', fontsize=12) plt.grid(linestyle='--', alpha=0.7)
for i, j in zip(x, y): plt.text(i, j+0.5, f'{j}', ha='center', va='bottom', fontsize=10)
plt.show()
|
三、饼图 (Pie Chart)
饼图适用于展示各部分占总体的比例关系。
3.1 基本饼图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import matplotlib.pyplot as plt import numpy as np
labels = ['A', 'B', 'C', 'D'] sizes = [15, 30, 45, 10] colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
plt.figure(figsize=(8, 8)) plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
plt.axis('equal')
plt.title('基本饼图', fontsize=15) plt.show()
|
3.2 环形图(甜甜圈图)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import matplotlib.pyplot as plt import numpy as np
labels = ['A', 'B', 'C', 'D'] sizes = [15, 30, 45, 10] colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99'] explode = (0.1, 0, 0, 0)
plt.figure(figsize=(8, 8)) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90, wedgeprops={'width': 0.3})
plt.axis('equal')
plt.title('环形图(甜甜圈图)', fontsize=15) plt.show()
|
四、其他常用图表
4.1 散点图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import matplotlib.pyplot as plt import numpy as np
np.random.seed(42) x = np.random.randn(100) y = np.random.randn(100) colors = np.random.rand(100) sizes = 1000 * np.random.rand(100)
plt.figure(figsize=(10, 10)) scatter = plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar(scatter, label='颜色值')
plt.title('散点图', fontsize=15) plt.xlabel('X轴', fontsize=12) plt.ylabel('Y轴', fontsize=12) plt.grid(linestyle='--', alpha=0.7)
plt.show()
|
4.2 直方图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import matplotlib.pyplot as plt import numpy as np import seaborn as sns
sns.set_style("whitegrid")
np.random.seed(42) data = np.random.randn(1000)
plt.figure(figsize=(12, 6)) sns.histplot(data, bins=30, kde=True, color='teal', edgecolor='black')
plt.title('直方图(带密度曲线)', fontsize=15) plt.xlabel('数值', fontsize=12) plt.ylabel('频数', fontsize=12)
plt.show()
|
4.3 箱线图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import matplotlib.pyplot as plt import numpy as np import seaborn as sns
sns.set_style("whitegrid")
np.random.seed(42) data = [np.random.normal(0, std, 100) for std in range(1, 5)] labels = ['组1', '组2', '组3', '组4']
plt.figure(figsize=(12, 6)) sns.boxplot(data=data, palette='Set2') plt.xticks(range(len(labels)), labels)
plt.title('箱线图', fontsize=15) plt.xlabel('组别', fontsize=12) plt.ylabel('数值', fontsize=12)
plt.show()
|
总结
本文档提供了Python中常用图表的生成代码示例,涵盖了条形图、折线图、饼图等基本类型,以及散点图、直方图、箱线图等扩展类型。每个示例代码均包含数据准备、图表绘制和样式自定义部分,用户可根据实际需求进行修改和扩展。
如需保存图表,可在plt.show()前添加以下代码:
1 2 3 4 5
| plt.savefig('图表名称.png', dpi=300, bbox_inches='tight')
plt.savefig('图表名称.pdf', bbox_inches='tight')
|
建议结合Matplotlib和Seaborn的官方文档,探索更多高级自定义选项和图表类型。