欢迎访问宙启技术站
智能推送

Python中的数据可视化库介绍与实例演示

发布时间:2024-01-14 21:22:04

Python中常用的数据可视化库有matplotlib、seaborn和plotly等。

1. matplotlib:

matplotlib是Python中最常用的数据可视化库,提供了丰富的绘图函数和样式选项。可以用于绘制折线图、散点图、柱状图、饼图等各种统计图形。

   import matplotlib.pyplot as plt

   # 绘制折线图
   x = [1, 2, 3, 4, 5]
   y = [1, 4, 9, 16, 25]
   plt.plot(x, y)

   # 绘制散点图
   x = [1, 2, 3, 4, 5]
   y = [1, 4, 9, 16, 25]
   plt.scatter(x, y)

   # 绘制柱状图
   x = [1, 2, 3, 4, 5]
   y = [1, 4, 9, 16, 25]
   plt.bar(x, y)

   # 绘制饼图
   labels = ['A', 'B', 'C', 'D']
   sizes = [45, 30, 15, 10]
   plt.pie(sizes, labels=labels)
   

2. seaborn:

seaborn是在matplotlib基础上开发的高级数据可视化库,提供了更美观和更专业的统计图形。seaborn支持绘制热力图、箱型图、小提琴图等常用的统计图形。

   import seaborn as sns

   # 绘制热力图
   data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
   sns.heatmap(data)

   # 绘制箱型图
   data = [1, 2, 3, 4, 5, 6]
   sns.boxplot(data)

   # 绘制小提琴图
   data = [1, 2, 3, 4, 5, 6]
   sns.violinplot(data)
   

3. plotly:

plotly是一款交互性数据可视化库,可以生成动态的可视化图表,并支持在网页上进行交互操作。plotly可以绘制折线图、散点图、3D图等各种类型的图形。

   import plotly.express as px

   # 绘制折线图
   x = [1, 2, 3, 4, 5]
   y = [1, 4, 9, 16, 25]
   fig = px.line(x=x, y=y)
   fig.show()

   # 绘制散点图
   x = [1, 2, 3, 4, 5]
   y = [1, 4, 9, 16, 25]
   fig = px.scatter(x=x, y=y)
   fig.show()

   # 绘制3D图
   import numpy as np
   x = np.linspace(0, 1, 100)
   y = np.linspace(0, 2, 100)
   X, Y = np.meshgrid(x, y)
   Z = np.sin(X) + np.sin(Y)
   fig = px.scatter_3d(x=X.flatten(), y=Y.flatten(), z=Z.flatten())
   fig.show()
   

以上示例介绍了三种常用的数据可视化库及其常见的图形类型的绘制方法。这些库可以根据自己的需求选择使用,并且都具有详细的文档和丰富的教程,方便学习和使用。