ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 1. Plotly 主要特点
  • 2. Plotly Express 基本使用
    • 2.1 基本图表创建
    • 2.2 常用图表类型
  • 3. 图表定制化
    • 3.1 布局调整
    • 3.2 样式调整
    • 3.3 子图创建
  • 4. 高级功能
    • 4.1 动画图表
    • 4.2 地图可视化
    • 4.3 与 Pandas 集成
  • 5. 输出与分享
    • 5.1 保存图表
    • 5.2 在Dash中使用
  • 6. 学习资源

Plotly 是一个强大的 Python 交互式可视化库,可以创建丰富的、可交互的图表。Plotly Express (px) 是其高级接口,简化了许多常见图表类型的创建过程。

1. Plotly 主要特点 #

  1. 交互性:所有图表都是交互式的,支持缩放、平移、悬停查看数据等
  2. 多样化图表:支持超过40种图表类型
  3. 美观默认样式:自动应用专业设计的配色和布局
  4. 多平台支持:可在 Jupyter Notebook、Dash 应用和静态HTML中工作
  5. 3D支持:轻松创建3D可视化

2. Plotly Express 基本使用 #

2.1 基本图表创建 #

如何使用 Plotly Express 创建最基础的交互式散点图。首先导入库,加载内置数据集,然后绘制并显示图表。适用于数据探索和可视化入门。

# 导入 Plotly Express 库
import plotly.express as px

# 使用内置鸢尾花数据集
df = px.data.iris()

# 创建散点图,x轴为萼片宽度,y轴为萼片长度,按种类着色
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
# 显示图表
fig.show()

2.2 常用图表类型 #

Plotly Express 支持的多种常用图表类型,包括折线图、柱状图、直方图、箱线图、散点矩阵图和3D散点图。每种图表都适用于不同的数据分析场景。

# 折线图,适合时间序列或趋势分析
gx_line = px.line(df, x="date", y="value", color="category")

# 柱状图,适合分类数据对比
gx_bar = px.bar(df, x="category", y="value", color="sub_category")

# 直方图,适合分布分析
gx_hist = px.histogram(df, x="value", nbins=30)

# 箱线图,适合统计分布和异常值分析
gx_box = px.box(df, x="group", y="value")

# 散点矩阵图,适合多变量相关性分析
gx_matrix = px.scatter_matrix(df, dimensions=["col1", "col2", "col3"], color="category")

# 3D散点图,适合三维空间数据可视化
gx_3d = px.scatter_3d(df, x="x", y="y", z="z", color="category")

3. 图表定制化 #

3.1 布局调整 #

图表布局调整可以自定义标题、坐标轴、字体、悬停模式等,提升图表的专业性和美观度。

# 更新图表布局,设置主标题、坐标轴标题、字体和悬停模式
fig.update_layout(
    # 设置图表主标题
    title="自定义标题",
    # 设置X轴标题
    xaxis_title="X轴标题",
    # 设置Y轴标题
    yaxis_title="Y轴标题",
    # 设置全局字体样式
    font=dict(family="Arial", size=12, color="darkblue"),
    # 设置悬停提示模式
    hovermode="x unified"
)

3.2 样式调整 #

通过 update_traces 可以调整图表的标记点样式,如大小、边框等,增强视觉效果。

# 更新图表标记点样式
fig.update_traces(
    # 设置标记点大小和边框
    marker=dict(size=12, line=dict(width=2, color="DarkSlateGrey")),
    # 只应用于散点图
    selector=dict(mode="markers")
)

3.3 子图创建 #

通过 make_subplots 可以将多个图表组合在一个画布上,适合多视图对比分析。

# 导入子图和基础图形对象
from plotly.subplots import make_subplots
import plotly.graph_objects as go

# 创建1行2列的子图布局
fig = make_subplots(rows=1, cols=2)

# 添加折线图到第1列
fig.add_trace(go.Scatter(x=[1,2,3], y=[4,5,6]), row=1, col=1)
# 添加柱状图到第2列
fig.add_trace(go.Bar(x=[1,2,3], y=[6,5,4]), row=1, col=2)

# 显示子图
fig.show()

4. 高级功能 #

4.1 动画图表 #

动画图表可以展示数据随时间或其他变量的动态变化,适合演示趋势和演化过程。

# 创建带动画的散点图,animation_frame 控制动画帧
px.scatter(df, x="gdp", y="life_exp", animation_frame="year", 
           size="pop", color="continent", hover_name="country")

4.2 地图可视化 #

地图可视化适合展示地理分布数据,支持动态变化。

# 创建动态地理热力图,locations 指定国家,color 指定数值
px.choropleth(df, locations="iso_alpha", color="value", 
              hover_name="country", animation_frame="year")

4.3 与 Pandas 集成 #

Plotly 可直接与 Pandas 数据框集成,支持多列同时绘图。

# 导入 pandas 库
import pandas as pd
# 读取本地 CSV 文件
df = pd.read_csv("data.csv")
# 绘制多列折线图
px.line(df, x="date", y=df.columns[1:])

5. 输出与分享 #

5.1 保存图表 #

Plotly 图表可以导出为 HTML 或图片,便于分享和嵌入网页。

# 保存为HTML文件
fig.write_html("chart.html")

# 保存为图片(需安装 orca 或 kaleido)
fig.write_image("chart.png")

5.2 在Dash中使用 #

Plotly 图表可无缝集成到 Dash Web 应用中,实现交互式数据展示。

# 导入 Dash 相关库
from dash import Dash, dcc, html

# 创建 Dash 应用
app = Dash(__name__)
# 设置页面布局,嵌入 Plotly 图表
app.layout = html.Div([dcc.Graph(figure=fig)])
# 启动服务器
app.run_server(debug=True)

6. 学习资源 #

  1. 官方文档:https://plotly.com/python/
  2. 图表示例库:https://plotly.com/python-api-reference/
  3. GitHub仓库:https://github.com/plotly/plotly.py

Plotly 特别适合需要交互式可视化的场景,相比 Matplotlib 和 Seaborn,它在动态展示和网页集成方面有显著优势。

访问验证

请输入访问令牌

Token不正确,请重新输入