1. Matplotlib
Matplotlib 是 Python 中最常用的数据可视化库之一,它提供了一整套绘图功能,可以生成各种类型的图表,如线图、散点图、柱状图、饼图等。以下是使用 Matplotlib 创建一个简单的线图的示例代码:
import matplotlib.pyplot as plt
# 数据
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# 创建图表
plt.plot(x, y)
# 添加标题和标签
plt.title('Simple Line Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
# 显示图表
plt.show()
2. Seaborn
Seaborn 是基于 Matplotlib 的一个高级可视化库,它提供了更高级的接口和丰富的图表类型,特别适合于统计数据的可视化。以下是一个使用 Seaborn 创建散点图的示例:
import seaborn as sns
import matplotlib.pyplot as plt
# 加载数据集
tips = sns.load_dataset('tips')
# 创建散点图
sns.scatterplot(x='total_bill', y='tip', hue='smoker', data=tips)
# 显示图表
plt.show()
3. Plotly
Plotly 是一个交互式图表库,它支持多种图表类型,包括散点图、柱状图、线图、地图等。以下是一个使用 Plotly 创建交互式线图的示例:
import plotly.express as px
# 数据
df = px.data.goog_nasdaq_daily()
# 创建交互式线图
fig = px.line(df, x='date', y='open', title='Stock Price Over Time')
# 显示图表
fig.show()
4. Bokeh
Bokeh 是一个交互式可视化库,它可以在网页上创建高性能的图表。以下是一个使用 Bokeh 创建交互式柱状图的示例:
from bokeh.plotting import figure, show
from bokeh.io import output_file, show
# 数据
data = {"x": ["Apples", "Bananas", "Cherries"], "y": [1, 2, 3]}
# 创建柱状图
p = figure(title="Column Chart", x_axis_label='Fruit', y_axis_label='Count')
p.vbar(x='x', top='y', width=0.9, source=data)
# 保存并显示图表
output_file("column.html")
show(p)
5. Altair
Altair 是一个声明式统计可视化库,它提供了简洁的语法来创建图表。以下是一个使用 Altair 创建条形图的示例:
import altair as alt
from vega_datasets import data
# 加载数据集
source = data.cars()
# 创建条形图
chart = alt.Chart(source).mark_bar().encode(
x='Horsepower:Q',
y='Count()',
color='Origin:N'
)
# 显示图表
chart.display()
以上是 Python 中五大热门数据可视化库的简要介绍和示例代码。每个库都有其独特的特点和优势,可以根据不同的需求选择合适的库来进行数据可视化。
