开始学习Python数据可视化
一.基础绘图函数
1.创建画布与坐标轴
import matplotlib.pyplot as plt# 创建画布和坐标轴
fig, ax = plt.subplots() # 默认1行1列,返回Figure对象和Axes对象
2.绘制线图
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]# 绘制线图
ax.plot(x, y, color='red', linestyle='--', marker='o', label='Line 1')
3. 绘制散点图
ax.scatter(x, y, color='blue', marker='^', label='Scatter')
4. 绘制柱状图
categories = ['A', 'B', 'C', 'D']
values = [30, 45, 15, 60]ax.bar(categories, values, color='green', alpha=0.6, label='Bar')
二、图表装饰函数
1. 标题与标签
ax.set_title("My Plot") # 标题
ax.set_xlabel("X Axis") # X轴标签
ax.set_ylabel("Y Axis") # Y轴标签
2. 图例与网格
ax.legend() # 显示图例
ax.grid(True, linestyle=':') # 显示虚线网格
3. 坐标轴范围与刻度
ax.set_xlim(0, 5) # X轴范围
ax.set_ylim(0, 70) # Y轴范围
ax.set_xticks([0, 2, 4]) # 设置X轴刻度
ax.set_xticklabels(['Start', 'Mid', 'End']) # 自定义刻度标签
三、多图与子图
1. 多子图布局
fig, axes = plt.subplots(2, 2) # 创建2行2列的子图
axes[0, 0].plot(x, y) # 在第一个子图绘制
axes[1, 1].scatter(x, y) # 在右下角子图绘制
2. 调整布局
plt.tight_layout() # 自动调整子图间距
四、保存与显示图像
1. 保存图像
plt.savefig('plot.png', dpi=300, bbox_inches='tight') # 保存为PNG
2. 显示图像
plt.show() # 显示所有已绘制的图形
五、常用样式设置
1. 全局样式
plt.style.use('ggplot') # 使用预定义样式(如 'ggplot', 'seaborn')
2. 文本标注
ax.text(2, 50, 'Peak', fontsize=12, color='purple') # 在坐标(2,50)添加文本
例子
import matplotlib.pyplot as plt# 创建画布和坐标轴
fig, ax = plt.subplots(figsize=(8, 5))# 绘制线图
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
ax.plot(x, y, 'r--o', label='Sales')# 装饰图表
ax.set_title("Sales Report")
ax.set_xlabel("Quarter")
ax.set_ylabel("Revenue (k)")
ax.legend()
ax.grid(True)# 显示图像
plt.show()