使用Matplotlib进行 Python 数据可视化
学习用 Python 绘制数据。在浏览器中创建清晰的散点图,调整标签、图例和本机样式。
概述
数据可视化是信息和数据的图形表示。通过使用图表、图形和地图等视觉元素,数据可视化工具提供了一种查看趋势、异常值和模式的便捷方式。
Matplotlib是 Python 中绘图的核心库。它提供了面向对象的 API,可让您自定义图形的每个像素,从轴颜色到字体样式。
在此示例中,我们生成合成增长曲线并将它们绘制在同一图上,展示如何为可发布的图表定义线条粗细、标记、图例和轴限制。
代码和执行输出
使用 matplotlib 渲染数学函数比较图表的脚本。
data_viz.py
在编辑器中尝试import matplotlib.pyplot as plt
import numpy as np
# Generate points along the X axis
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create figure
fig, ax = plt.subplots(figsize=(8, 5))
# Plot lines
ax.plot(x, y1, label='Sine Wave', color='#0D9488', linewidth=2.5)
ax.plot(x, y2, label='Cosine Wave', color='#EF4444', linewidth=2, linestyle='--')
# Style axis and frame
ax.set_title('Trigonometric Waveforms', fontsize=14, fontweight='bold', pad=15)
ax.set_xlabel('X Axis (Radians)', fontsize=11)
ax.set_ylabel('Amplitude', fontsize=11)
ax.grid(True, linestyle=':', alpha=0.6)
ax.legend(loc='upper right', frameon=True)
ax.spines[['top', 'right']].set_visible(False)
plt.tight_layout()
plt.show()端子输出
Rendered visualization in the Graphs tab...逐步实施
- 科学研究绘图和遥测输出
- 为分析 Web 应用程序创建仪表板图表元素
- 机器学习任务期间的探索性数据分析
常见问题解答
我可以将seaborn 与PyRun一起使用吗?
是的,seaborn 是一个构建在 matplotlib 之上的包装器。如果导入,PyRun会将其绘图重定向到同一浏览器图形视口中。
如何将 matplotlib 图保存到 Python 中的文件中?
您可以运行 plt.savefig('my_chart.png', dpi=300)` 将图像直接写入文件系统工作区,而不是调用 `plt.show()`。