Python Dataviz
2026-03-28
新闻来源:网淘吧
围观:16
电脑广告
手机广告
Python 数据可视化
使用 Python 领先的库创建专业的图表、图形和统计可视化。
库与使用场景
matplotlib- 静态绘图,出版级质量,完全控制
- 条形图、折线图、散点图、饼图、直方图、热力图
- 多面板图形,子图
- 自定义样式,标注
- 导出格式:PNG, SVG, PDF
seaborn- 统计可视化,精美的默认设置
- 分布图(小提琴图、箱线图、核密度估计图、直方图)
- 分类图(条形图、计数图、蜂群图、箱线图)
- 关系图(散点图、折线图、回归图)
- 矩阵图(热力图、聚类图)
- 基于 matplotlib 构建,无缝集成
plotly- 交互式图表,适合网页
- 悬停提示框,缩放,平移
- 3D 图,动画
- 通过Dash框架创建仪表盘
- 导出格式:HTML、PNG(需安装kaleido)
快速入门
环境设置
cd skills/python-dataviz
python3 -m venv .venv
source .venv/bin/activate
pip install .
创建图表
import matplotlib.pyplot as plt
import numpy as np
# Data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, linewidth=2, color='#667eea')
plt.title('Sine Wave', fontsize=16, fontweight='bold')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.grid(alpha=0.3)
plt.tight_layout()
# Export
plt.savefig('output.png', dpi=300, bbox_inches='tight')
plt.savefig('output.svg', bbox_inches='tight')
图表选择指南
分布/统计类:
- 直方图 →
plt.hist()或sns.histplot() - 箱形图 →
sns.boxplot() - 小提琴图 →
sns.violinplot() - 核密度估计图 →
sns.kdeplot()
比较类:
- 条形图 →
plt.bar()或sns.barplot() - 分组条形图 →
sns.barplot(hue=...) - 水平条形图 →
plt.barh()或者sns.barplot(orient='h')
关系:
- 散点图 →
plt.scatter()或者sns.scatterplot() - 折线图 →
plt.plot()或者sns.lineplot() - 回归图 →
sns.regplot()或者sns.lmplot()
热力图:
- 相关性矩阵 →
sns.heatmap(df.corr()) - 二维数据 →
plt.imshow()或者sns.heatmap()
交互式:
- 任何 Plotly 图表 →
plotly.express或plotly.graph_objects - 参见 references/plotly-examples.md
最佳实践
1. 图形尺寸与 DPI
plt.figure(figsize=(10, 6)) # Width x Height in inches
plt.savefig('output.png', dpi=300) # Publication: 300 dpi, Web: 72-150 dpi
2. 调色板
# Seaborn palettes (works with matplotlib too)
import seaborn as sns
sns.set_palette("husl") # Colorful
sns.set_palette("muted") # Soft
sns.set_palette("deep") # Bold
# Custom colors
colors = ['#667eea', '#764ba2', '#f6ad55', '#4299e1']
3. 样式设置
# Use seaborn styles even for matplotlib
import seaborn as sns
sns.set_theme() # Better defaults
sns.set_style("whitegrid") # Options: whitegrid, darkgrid, white, dark, ticks
# Or matplotlib styles
plt.style.use('ggplot') # Options: ggplot, seaborn, bmh, fivethirtyeight
4. 多子图
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
axes[0, 0].plot(x, y1)
axes[0, 1].plot(x, y2)
# etc.
plt.tight_layout() # Prevent label overlap
5. 导出格式
# PNG for sharing/embedding (raster)
plt.savefig('chart.png', dpi=300, bbox_inches='tight', transparent=False)
# SVG for editing/scaling (vector)
plt.savefig('chart.svg', bbox_inches='tight')
# For plotly (interactive)
import plotly.express as px
fig = px.scatter(df, x='col1', y='col2')
fig.write_html('chart.html')
高级主题
参见 references/ 获取详细指南:
- 色彩理论与调色板: references/colors.md
- 统计图表: references/statistical.md
- Plotly 交互式图表: references/plotly-examples.md
- 多面板布局: references/layouts.md
示例脚本
参见 scripts/ 获取即用示例:
scripts/bar_chart.py- 条形图与分组条形图scripts/line_chart.py- 多系列折线图scripts/scatter_plot.py- 带回归分析的散点图scripts/heatmap.py- 相关性热力图scripts/distribution.py- 直方图、核密度估计图、小提琴图scripts/interactive.py- Plotly交互式图表
常见模式
来自CSV的数据
import pandas as pd
df = pd.read_csv('data.csv')
# Plot with pandas (uses matplotlib)
df.plot(x='date', y='value', kind='line', figsize=(10, 6))
plt.savefig('output.png', dpi=300)
# Or with seaborn for better styling
sns.lineplot(data=df, x='date', y='value')
plt.savefig('output.png', dpi=300)
字典数据
data = {'Category A': 25, 'Category B': 40, 'Category C': 15}
# Matplotlib
plt.bar(data.keys(), data.values())
plt.savefig('output.png', dpi=300)
# Seaborn (convert to DataFrame)
import pandas as pd
df = pd.DataFrame(list(data.items()), columns=['Category', 'Value'])
sns.barplot(data=df, x='Category', y='Value')
plt.savefig('output.png', dpi=300)
NumPy数组
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.savefig('output.png', dpi=300)
故障排除
"没有名为matplotlib的模块"
cd skills/python-dataviz
source .venv/bin/activate
pip install -r requirements.txt
空白输出 / "图形为空"
- 请检查
plt.savefig()是否位于绘图命令之后 - 开发时使用
plt.show()进行交互式查看
标签被截断
plt.tight_layout() # Add before plt.savefig()
# Or
plt.savefig('output.png', bbox_inches='tight')
低分辨率输出
plt.savefig('output.png', dpi=300) # Not 72 or 100
环境
该技能包含一个已安装所有依赖项的虚拟环境。使用前请务必激活:
cd /home/matt/.openclaw/workspace/skills/python-dataviz
source .venv/bin/activate
依赖项:matplotlib、seaborn、plotly、pandas、numpy、kaleido(用于plotly静态导出)
文章底部电脑广告
手机广告位-内容正文底部


微信扫一扫,打赏作者吧~