plotly について
Plotlyは、分析担当者や開発者向けのPythonインタラクティブ可視化ツールです。簡潔なPlotly Express APIと、Graph Objectsによる細かなチャート制御を備えています。
主な機能
- 01インタラクティブな統計チャート
- 023D・地理空間の可視化
- 03アニメーションと時系列チャート
- 04チャートのHTML出力
- 05Graph Objectsによる詳細制御
活用シーン
- 01Notebookでのデータ探索
- 02インタラクティブなWebチャートの作成
- 03Dashダッシュボードの構築
- 04共有用HTMLレポートの生成
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ tondevrel/ scientific-agent-skills --skill plotlyインストール後、Claude Code で/plotlyを入力して読み込まれたか確認します。
詳細
Plotly - インタラクティブな可視化
Plotly は、幅広いインタラクティブチャートを提供します。「Plotly Express」API は、整然とした DataFrame を使った高速で簡単な操作を目的に設計されています。一方、「Graph Objects」では、すべてのトレースと属性を低レベルで制御できます。
使用する場面
- Web アプリケーションや Jupyter ノートブック用のインタラクティブチャートを作成するとき
- 3D データ(サーフェス、散布図、メッシュ)を可視化するとき
- Mapbox と連携した地理マップ(地図上の散布図、コロプレス図)を作成するとき
- 金融チャート(ローソク足、OHLC)を作成するとき
- 特定の領域をズームして調べる必要がある大規模なデータセットを探索するとき
- アニメーション(時系列スライダー)を作成するとき
- 本番環境に対応したダッシュボードを構築するとき(Dash 経由)
リファレンスドキュメント
公式ドキュメント: https://plotly.com/python/
Plotly Express: https://plotly.com/python/plotly-express/
検索パターン: px.scatter、go.Figure、fig.update_layout、fig.write_html、px.choropleth
基本原則
Plotly Express(px)と Graph Objects(go)の比較
| 特徴 | Plotly Express(px) | Graph Objects(go) |
|---|---|---|
| 複雑さ | 高レベルで簡潔です。 | 低レベルで冗長です。 |
| データ形式 | 整然とした(ロング形式の)DataFrame。 | リスト、配列、辞書、または DataFrame。 |
| カスタマイズ | 良好(update_* を使用)。 | 最大限の制御が可能です。 |
| 開発速度 | 非常に高速です。 | より低速です。 |
Plotly を使う場面
- インタラクティブな探索(ホバー、ズーム)
- 3D および地理空間の可視化
- 単体で動作するインタラクティブな HTML ファイルへのエクスポート
- Dash との連携
Plotly を使わない場面
- 出版品質の静的な LaTeX プロット(Matplotlib を使用してください)
- 非常に大きな静的画像の生成(Matplotlib のほうが高速です)
- メモリの少ない環境(Plotly の JSON ベースの図はメモリを大量に消費します)
クイックリファレンス
インストール
pip install plotly pandas
標準インポート
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
基本パターン - Plotly Express
import plotly.express as px
# Load data
df = px.data.iris()
# Create interactive scatter plot
fig = px.scatter(df, x="sepal_width", y="sepal_length",
color="species", size="petal_length",
hover_data=['petal_width'])
# Display
fig.show()
重要なルール
✅ すること
- まず Plotly Express を使う — タスクの 90% は px のほうが簡単です
- 整然としたデータを優先する — 色や軸へのマッピングを簡単にするため、観測値ごとに 1 行にします
- update_layout を使う — タイトル、フォント、背景色をすっきりと変更できます
- HTML として保存する —
fig.write_html("plot.html")を使ってインタラクティブチャートを共有します - ホバーデータを活用する — プロットを見づらくせずに、ポイントにコンテキストを追加できます
- 図のテンプレートを設定する —
template="plotly_dark"または"ggplot2"を使って、すぐにスタイルを適用します - marginal_x/y を使う — px.scatter で、ヒストグラムや箱ひげ図を余白にすばやく追加できます
❌ しないこと
- 巨大なデータセットをブラウザーに渡す — 50k を超えるポイントをプロットすると UI が遅くなる場合があります。datashader または間引きを使用してください
- go で手動ループする — px でできる場合は、go でトレースを追加するための for ループを使わないでください
- 軸ラベルの設定を忘れる — px は列名を使用します。ラベルを見やすくするため、DataFrame で列名を変更してください
- アニメーションを多用する — 滑らかなアニメーションは魅力的ですが、動く要素が多すぎるとデータへの注意がそれます
アンチパターン(絶対に避けること)
# ❌ BAD: Over-complicating a simple plot with Graph Objects
fig = go.Figure()
for species in df['species'].unique():
sub = df[df['species'] == species]
fig.add_trace(go.Scatter(x=sub['sepal_w'], y=sub['sepal_l'], name=species))
# ✅ GOOD: Use Plotly Express (One line, automatic legend/colors)
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
# ❌ BAD: Mixing list-style data with DataFrame-style data in px
px.scatter(x=[1,2,3], y=df['column']) # Can lead to alignment issues
# ✅ GOOD: Stick to the DataFrame
px.scatter(df, x="column_a", y="column_b")
Plotly Express(px)の詳細
統計チャート
# Boxplot with points
fig = px.box(df, x="day", y="total_bill", color="smoker", points="all")
# Violin plot with box inside
fig = px.violin(df, x="day", y="total_bill", color="sex", box=True, points="all")
# Heatmap (Density Contour)
fig = px.density_heatmap(df, x="total_bill", y="tip", marginal_x="histogram", marginal_y="histogram")
時系列とファセット
df = px.data.stocks()
# Multiple lines from wide data
fig = px.line(df, x='date', y=["GOOG", "AAPL", "AMZN"], title="Tech Stocks")
# Faceting (Subplots by category)
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker",
facet_col="day", facet_row="time")
3D 可視化
散布図、線、サーフェス
# 3D Scatter
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width', color='species')
# 3D Surface (Using Graph Objects)
z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')
fig = go.Figure(data=[go.Surface(z=z_data.values)])
fig.update_layout(title='Mt Bruno Elevation', autosize=False,
width=500, height=500, margin=dict(l=65, r=50, b=65, t=90))
地理空間分析
マップとコロプレス図
# Scatter on a map
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df, locations="iso_alpha", color="continent",
hover_name="country", size="pop",
projection="natural earth")
# Detailed Mapbox Choropleth (Needs token or use open-street-map)
fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
mapbox_style="carto-positron",
zoom=3, center = {"lat": 37.0902, "lon": -95.7129})
レイアウトとスタイル(fig.update_*)
外観の微調整
fig = px.scatter(df, x="x", y="y")
# Global layout updates
fig.update_layout(
title="Custom Styled Plot",
xaxis_title="Dimension X",
yaxis_title="Dimension Y",
font=dict(family="Courier New, monospace", size=18, color="RebeccaPurple"),
legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01),
plot_bgcolor="white"
)
# Axis specific updates
fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='LightPink')
fig.update_yaxes(zeroline=True, zerolinewidth=2, zerolinecolor='Black')
高度なインタラクション:アニメーション
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year",
animation_group="country",
size="pop", color="continent", hover_name="country",
log_x=True, size_max=55, range_x=[100, 100000], range_y=[25, 90])
実践的なワークフロー
1. インタラクティブな科学レポートのエクスポート
def create_interactive_report(df, filename="report.html"):
"""Generates a multi-chart HTML report."""
fig1 = px.scatter(df, x="A", y="B", color="C")
fig2 = px.histogram(df, x="A", color="C")
with open(filename, 'a') as f:
f.write(fig1.to_html(full_html=False, include_plotlyjs='cdn'))
f.write(fig2.to_html(full_html=False, include_plotlyjs='cdn'))
# Useful for sharing findings with non-technical stakeholders
2. 金融ダッシュボードの一部(ローソク足)
import pandas as pd
from datetime import datetime
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
fig = go.Figure(data=[go.Candlestick(x=df['Date'],
open=df['AAPL.Open'],
high=df['AAPL.High'],
low=df['AAPL.Low'],
close=df['AAPL.Close'])])
# Remove rangeslider for cleaner look
fig.update_layout(xaxis_rangeslider_visible=False)
3. go.Figure でサブプロットを組み合わせる
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2, subplot_titles=("Plot A", "Plot B"))
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1)
fig.add_trace(go.Bar(x=[1, 2, 3], y=[2, 3, 5]), row=1, col=2)
fig.update_layout(height=600, width=800, title_text="Side-by-Side Comparison")
パフォーマンスの最適化
大規模データセット向けの WebGL
# For scatter plots with >10,000 points, use Scattergl (Graph Objects)
# or tell px to use webgl (available in newer versions)
fig = px.scatter(df, x="large_x", y="large_y", render_mode="webgl")
# WebGL drastically improves performance by using the GPU for rendering.
よくある問題と解決策
ノートブックでの JSON オーバーヘッド
# ❌ Problem: Notebook file size explodes to 50MB
# ✅ Solution: Display as static image (requires kaleido) or use a different renderer
# fig.show(renderer="png") # Static
# OR: Clear output after viewing
アニメーションでの軸スケーリング
# ❌ Problem: Axes jump around during animation
# ✅ Solution: Manually fix the ranges
fig = px.scatter(df, x="x", y="y", animation_frame="time",
range_x=[0, 100], range_y=[0, 100])
凡例に表示されないカテゴリへの対処
# ❌ Problem: Colors change when filtering data because categories disappear
# ✅ Solution: Pass a category_orders dictionary
fig = px.scatter(df, x="x", y="y", color="category",
category_orders={"category": ["A", "B", "C", "D"]})
ベストプラクティス
- まずはPlotly Expressを使う - 90%のタスクでは
pxから始め、細かな制御が必要な場合にのみgoを使います - 整然としたDataFrameを使う - 視覚属性へのマッピングを容易にするため、観測値ごとに1行となるようにします
- スタイル設定には
update_layoutを使う - 図を作り直さずに、タイトル、フォント、背景色をすっきりと変更できます - 共有用にHTMLで保存する -
fig.write_html("plot.html")を使って、インタラクティブなチャートを関係者と共有します - ホバーデータを活用する - プロットを煩雑にせず、ポイントにコンテキストを追加します
- 図のテンプレートを設定する -
template="plotly_dark"または"ggplot2"を使って、すぐにプロフェッショナルなスタイルを適用します - 周辺プロットを使う -
px.scatterでmarginal_xとmarginal_yを使うと、ヒストグラムや箱ひげ図をすばやく追加できます - 大規模なデータセット向けに最適化する - 50k点を超えるデータセットには、WebGLレンダリングまたはdatashaderを使います
- アニメーションで軸範囲を固定する -
range_xとrange_yを使って、アニメーション中に軸が動かないようにします - カテゴリの順序を設定する -
category_ordersを使って、データをフィルタリングしても色の一貫性を保ちます
Plotlyは、静的な分析とインタラクティブな探索の橋渡しをします。ノートブックで得た科学的知見をウェブへ移すのに最適なツールです。
コメント
Markdown 対応