Plotly
是一个功能强大的 Python 库,用于创建交互式、可视化的图表,适用于数据分析、科学计算和仪表板开发。它支持多种图表类型(如折线图、散点图、柱状图、3D 图等),并生成可在浏览器中交互的 HTML 图表。Plotly
的子模块 plotly.express
提供了简洁的高层次 API,适合快速绘图,而 plotly.graph_objects
则提供更精细的控制。Plotly
图表可以导出为静态图像、嵌入 Web 应用,或与 Dash
和 Streamlit
集成。
以下是对 Plotly
库的详细介绍,包括其功能、用法和实际应用。
numpy
:数值计算。pandas
:数据处理。tenacity
:重试逻辑。pip install plotly
pip install jupyterlab
jupyter labextension install jupyterlab-plotly
kaleido
):pip install kaleido
import plotly
print(plotly.__version__) # 示例输出: 5.24.1
Plotly
提供两个主要接口:plotly.express
(高层次,快速绘图)和 plotly.graph_objects
(低层次,精细控制)。以下是主要功能和示例。
plotly.express
提供简洁的 API,适合快速生成常见图表。
import plotly.express as px
import pandas as pd
# 示例数据
df = pd.DataFrame({
"x": [1, 2, 3, 4],
"y": [10, 15, 13, 17],
"category": ["A", "B", "A", "B"]
})
# 折线图
fig = px.line(df, x="x", y="y", color="category", title="Line Chart")
fig.show()
说明:
px.line
:绘制折线图,color
指定分组。fig.show()
:在浏览器或 Jupyter 中显示交互式图表。散点图:
fig = px.scatter(df, x="x", y="y", color="category", size="y", title="Scatter Plot")
fig.show()
柱状图:
fig = px.bar(df, x="x", y="y", color="category", title="Bar Chart")
fig.show()
plotly.graph_objects
提供更灵活的配置,适合复杂图表。
import plotly.graph_objects as go
# 创建图表
fig = go.Figure()
fig.add_trace(go.Scatter(x=df["x"], y=df["y"], mode="lines+markers", name="Data"))
fig.update_layout(
title="Custom Line Chart",
xaxis_title="X Axis",
yaxis_title="Y Axis",
template="plotly_dark"
)
fig.show()
说明:
go.Scatter
:添加折线/散点轨迹。update_layout
:设置标题、轴标签、主题等。支持 3D 散点图、表面图等。
import plotly.express as px
import numpy as np
# 示例数据
z = np.random.rand(10, 10)
fig = px.imshow(z, title="Heatmap")
fig.show()
# 3D 散点图
df = px.data.iris()
fig = px.scatter_3d(df, x="sepal_length", y="sepal_width", z="petal_length", color="species")
fig.show()
说明:
px.imshow
:绘制热图。px.scatter_3d
:绘制 3D 散点图。支持地图和地理数据可视化。
import plotly.express as px
# 示例数据
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(
df,
locations="iso_alpha",
size="pop",
color="continent",
hover_name="country",
title="World Population"
)
fig.show()
说明:
px.scatter_geo
:绘制全球散点图,locations
使用 ISO 国家代码。Plotly
图表支持以下交互:
fig = px.line(df, x="x", y="y")
fig.update_traces(hovertemplate="X: %{x}
Y: %{y}")
fig.show()
说明:
hovertemplate
:自定义悬停提示。将图表保存为文件或嵌入 HTML。
# 保存为 PNG
fig.write_image("chart.png")
# 保存为 HTML
fig.write_html("chart.html")
# 保存为 JSON
fig.write_json("chart.json")
说明:
write_image
需安装 kaleido
。write_html
生成独立 HTML 文件,可嵌入网站。plotly
、plotly_dark
、seaborn
)。示例(Streamlit 集成):
import streamlit as st
import plotly.express as px
import pandas as pd
st.title("Interactive Plotly Dashboard")
# 数据
df = pd.DataFrame({
"x": range(10),
"y": [2, 4, 1, 5, 3, 6, 2, 7, 4, 8]
})
# 交互控件
chart_type = st.selectbox("Chart Type", ["Line", "Scatter"])
if chart_type == "Line":
fig = px.line(df, x="x", y="y")
else:
fig = px.scatter(df, x="x", y="y")
st.plotly_chart(fig)
说明:
fig.show()
在浏览器显示图表。import plotly.io as pio
pio.renderers.default = "notebook"
fig.show()
from dash import Dash, dcc, html
app = Dash(__name__)
app.layout = html.Div([dcc.Graph(figure=fig)])
app.run_server(debug=True)
import plotly.io as pio
pio.write_to_plotly(fig, filename="my-chart")
import plotly
plotly.tools.set_credentials_file(username="your_username", api_key="your_api_key")
plotly.express
的 render_mode="webgl"
:fig = px.scatter(df, x="x", y="y", render_mode="webgl")
fig.show()
。plotly
和可视化库(如 pandas
)版本兼容。kaleido
,可能因字体或系统配置报错。plotly.express
简单易学,graph_objects
需熟悉对象结构。以下是一个综合示例,展示多种图表类型和交互功能:
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
st.title("Plotly Visualization Dashboard")
# 示例数据
df = px.data.gapminder().query("year == 2007")
# 选择图表类型
chart_type = st.selectbox("Select Chart Type", ["Scatter", "Bar", "Geo"])
if chart_type == "Scatter":
fig = px.scatter(
df,
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
hover_name="country",
log_x=True,
title="GDP vs Life Expectancy"
)
elif chart_type == "Bar":
fig = px.bar(
df,
x="continent",
y="pop",
color="continent",
title="Population by Continent"
)
else:
fig = px.scatter_geo(
df,
locations="iso_alpha",
size="pop",
color="continent",
hover_name="country",
title="World Population Map"
)
# 自定义布局
fig.update_layout(
template="plotly_dark",
xaxis_title="X Axis",
yaxis_title="Y Axis"
)
# 显示图表
st.plotly_chart(fig)
# 保存选项
if st.button("Save as PNG"):
fig.write_image("chart.png")
st.write("Chart saved as chart.png")
说明: