mcpField
P
pgfplots

pgfplots

github.com/igbuendデータ・データベース975 回インストール33 週間前に更新
リポジトリ

pgfplots について

pgfplotsはLaTeX用の作図パッケージで、このスキルはデータ可視化の実用リファレンスです。グラフの種類、軸、スタイル、データファイル、よくある問題の対処法を扱います。

主な機能

  1. 01折れ線・散布図・棒グラフ
  2. 02統計グラフと3Dプロット
  3. 03軸と凡例のカスタマイズ
  4. 04データファイルからの作図
  5. 05よくあるエラーの対処

活用シーン

  1. 01LaTeX文書用のグラフ作成
  2. 02CSVファイルの値のプロット
  3. 03グループ図や複数軸の図の作成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/igbuend/grimbard --skill pgfplots

インストール後、Claude Code で/pgfplotsを入力して読み込まれたか確認します。

詳細

pgfplots — データの可視化とプロット

CTAN: https://ctan.org/pkg/pgfplots
マニュアル: texdoc pgfplots

セットアップ

\usepackage{pgfplots}
\pgfplotsset{compat=1.18}  % ALWAYS set this — enables latest features

% Optional libraries
\usepgfplotslibrary{fillbetween, groupplots, statistics, colorbrewer, polar}

基本的なプロット

\begin{tikzpicture}
\begin{axis}[
  xlabel={$x$},
  ylabel={$f(x)$},
  title={My Plot},
  grid=major,
]
  \addplot[blue, thick, domain=-3:3, samples=100] {x^2};
  \addlegend{$x^2$}
\end{axis}
\end{tikzpicture}

軸環境

環境説明
axis標準的な線形軸
semilogxaxisx 軸を対数スケールにする
semilogyaxisy 軸を対数スケールにする
loglogaxis両軸を対数スケールにする
polaraxis極座標(polar ライブラリが必要)

軸オプションのリファレンス

オプション例説明
xlabelxlabel={Time (s)}x 軸のラベル
ylabelylabel={Voltage}y 軸のラベル
titletitle={Results}プロットのタイトル
xmin/xmaxxmin=0, xmax=10軸の範囲
ymin/ymaxymin=-1, ymax=1軸の範囲
domaindomain=0:2*piデフォルトのプロット範囲
samplessamples=200デフォルトのサンプル数
gridgrid=majormajor、minor、both、none
legend poslegend pos=north west凡例の配置
width/heightwidth=10cm軸の寸法
axis linesaxis lines=middlebox、left、middle、none
enlargelimitsenlargelimits=0.1軸の範囲に余白を追加
xtickxtick={0,1,...,5}目盛り位置を指定
xticklabelsxticklabels={A,B,C}目盛りラベルを指定
x tick label stylex tick label style={rotate=45}目盛りラベルの書式設定
legend stylelegend style={at={(0.5,-0.2)}}凡例のカスタマイズ
cycle list namecycle list name=color list色の循環
scaled ticksscaled ticks=false目盛りのスケーリングを無効化
restrict y to domainrestrict y to domain=-10:10極端な値をクリップ

プロットの種類と例

折れ線グラフ(式から作成)
\begin{axis}[domain=0:2*pi, samples=100, grid=major,
  legend pos=south west]
  \addplot[blue, thick] {sin(deg(x))};
  \addplot[red, thick, dashed] {cos(deg(x))};
  \legend{$\sin(x)$, $\cos(x)$}
\end{axis}
折れ線グラフ(データから作成)
\begin{axis}[xlabel=Year, ylabel=Value]
  \addplot coordinates {
    (2018, 10) (2019, 15) (2020, 12) (2021, 20) (2022, 25)
  };
\end{axis}
散布図
\begin{axis}[only marks, xlabel=$x$, ylabel=$y$]
  \addplot[mark=*, blue] coordinates {
    (1,2) (2,3.5) (3,2.8) (4,5.1) (5,4.2)
  };
  % Or with mark options:
  \addplot+[mark=o, mark size=3pt, red] coordinates { ... };
\end{axis}
棒グラフ
\begin{axis}[
  ybar,                    % vertical bars (xbar for horizontal)
  symbolic x coords={A, B, C, D},
  xtick=data,
  ylabel={Count},
  nodes near coords,       % value labels on bars
  bar width=15pt,
]
  \addplot coordinates {(A,20) (B,35) (C,30) (D,15)};
  \addplot coordinates {(A,25) (B,20) (C,40) (D,10)};
  \legend{2022, 2023}
\end{axis}
積み上げ棒グラフ
\begin{axis}[ybar stacked, symbolic x coords={Q1,Q2,Q3,Q4}, xtick=data]
  \addplot coordinates {(Q1,10) (Q2,15) (Q3,12) (Q4,18)};
  \addplot coordinates {(Q1,8)  (Q2,10) (Q3,15) (Q4,12)};
  \legend{Product A, Product B}
\end{axis}
ヒストグラム
\usepgfplotslibrary{statistics}

\begin{axis}[ybar interval, ylabel=Frequency, xlabel=Value]
  \addplot+[hist={bins=10, data min=0, data max=100}]
    table[y index=0] {data.csv};
\end{axis}
箱ひげ図
\usepgfplotslibrary{statistics}

\begin{axis}[boxplot/draw direction=y]
  \addplot[boxplot prepared={
    lower whisker=2, lower quartile=4,
    median=6, upper quartile=8, upper whisker=10
  }] coordinates {};
\end{axis}
面積塗りつぶし/曲線間の塗りつぶし
\usepgfplotslibrary{fillbetween}

\begin{axis}
  \addplot[name path=upper, blue, thick, domain=0:4] {x^2};
  \addplot[name path=lower, red, thick, domain=0:4] {x};
  \addplot[fill=blue!10] fill between[of=upper and lower, soft clip={domain=1:3}];
\end{axis}
エラーバー
\begin{axis}
  \addplot+[error bars/.cd, y dir=both, y explicit]
    coordinates {
      (1, 2) +- (0, 0.5)
      (2, 4) +- (0, 0.8)
      (3, 3) +- (0, 0.3)
    };
\end{axis}
3D サーフェス
\begin{axis}[view={45}{30}, xlabel=$x$, ylabel=$y$, zlabel=$z$,
  colormap/viridis]
  \addplot3[surf, domain=-2:2, domain y=-2:2, samples=25]
    {exp(-x^2 - y^2)};
\end{axis}
3D メッシュ
\begin{axis}[view={60}{30}]
  \addplot3[mesh, domain=-2:2, domain y=-2:2, samples=20]
    {sin(deg(x)) * cos(deg(y))};
\end{axis}
等高線
\begin{axis}[view={0}{90}]  % top-down view
  \addplot3[contour filled, domain=-2:2, domain y=-2:2, samples=30]
    {exp(-x^2 - y^2)};
\end{axis}
パラメトリックプロット
\begin{axis}[axis equal]
  \addplot[domain=0:360, samples=100, thick, blue]
    ({cos(x)}, {sin(x)});  % circle
\end{axis}
極座標プロット
\usepgfplotslibrary{polar}

\begin{polaraxis}
  \addplot[domain=0:360, samples=100, thick]
    {1 + cos(x)};  % cardioid
\end{polaraxis}

ファイルからのデータ

% CSV file: data.csv
% x, y
% 1, 2.3
% 2, 4.1
% ...

\begin{axis}
  \addplot table[col sep=comma, x=x, y=y] {data.csv};
  
  % TSV (default separator is space/tab)
  \addplot table[x index=0, y index=1] {data.tsv};
  
  % With expression on column
  \addplot table[x=time, y expr=\thisrow{value}*100] {data.csv};
\end{axis}

カラーマップ

% Built-in colormaps
colormap/hot, colormap/cool, colormap/viridis,
colormap/bluered, colormap/greenyellow, colormap/jet

% Custom
\pgfplotsset{
  colormap={mymap}{rgb255(0cm)=(0,0,180); rgb255(1cm)=(0,180,0); rgb255(2cm)=(180,0,0)}
}

% Colorbar
\begin{axis}[colorbar, colormap/viridis]

複数の軸

\begin{tikzpicture}
\begin{axis}[
  axis y line*=left, xlabel=Time, ylabel=Temperature,
  ymin=0, ymax=100,
]
  \addplot[blue, thick] coordinates {(1,20)(2,40)(3,60)(4,80)};
  \label{plot:temp}
\end{axis}

\begin{axis}[
  axis y line*=right, axis x line=none,
  ylabel=Pressure, ymin=0, ymax=10,
]
  \addplot[red, thick, dashed] coordinates {(1,2)(2,5)(3,3)(4,8)};
  \label{plot:press}
\end{axis}
\end{tikzpicture}

プロットのグループ化

\usepgfplotslibrary{groupplots}

\begin{tikzpicture}
\begin{groupplot}[
  group style={group size=2 by 2, horizontal sep=1.5cm, vertical sep=1.5cm},
  width=6cm, height=5cm,
]
  \nextgroupplot[title=Plot 1]
    \addplot {x};
  \nextgroupplot[title=Plot 2]
    \addplot {x^2};
  \nextgroupplot[title=Plot 3]
    \addplot {sqrt(x)};
  \nextgroupplot[title=Plot 4]
    \addplot {ln(x)};
\end{groupplot}
\end{tikzpicture}

注釈

\begin{axis}
  \addplot[blue, thick, domain=0:5] {x^2};
  
  % Pin annotation
  \node[pin=60:{Maximum}] at (axis cs:4, 16) {};
  
  % Arrow annotation
  \draw[->, thick] (axis cs:2, 10) -- (axis cs:3, 9)
    node[above, pos=0] {Note};
  
  % Vertical line
  \draw[dashed, gray] (axis cs:2.5, 0) -- (axis cs:2.5, 25);
  
  % Horizontal band
  \draw[fill=red!10, draw=none] (axis cs:0,5) rectangle (axis cs:5,10);
  
  % Text node
  \node at (axis cs:1, 20) {$f(x) = x^2$};
\end{axis}

マークのオプション

マーク説明
*塗りつぶし円
o白抜き円
square*塗りつぶし四角形
square白抜き四角形
triangle*塗りつぶし三角形
diamond*塗りつぶしひし形
x交差
+プラス
star星
noneマークなし
\addplot+[mark=triangle*, mark size=3pt, mark options={fill=red}] ...;

よくある落とし穴

問題原因対処法
"Dimension too large"値または範囲が大きすぎるrestrict y to domain を使用し、範囲を確認する
compat 警告が表示される\pgfplotsset{compat=..} がない\pgfplotsset{compat=1.18} を追加する
三角関数の結果が正しくないpgfplots は度数法を使用するラジアン入力には sin(deg(x)) を使用する
棒が重なって表示されるグループ化せずに複数の棒グラフを作成しているbar shift または凡例とともに ybar を使用する
凡例の位置が正しくないデフォルトの位置が使われているlegend pos=north west などを設定する
3D プロットが遅すぎるサンプル数が多すぎる3D プロットでは samples を減らす
軸ラベルが切れているバウンディングボックスが狭すぎるtrim axis left/right を使用するか、余白を広げる
曲線間の塗りつぶしが失敗するパスに名前が付いていない各プロットに name path=A を追加する
CSV 列のエラー区切り文字が正しくないCSV ファイルには col sep=comma を設定する
\addlegendentry の順序対応する \addplot の後に置く必要がある凡例項目を対応するプロットの直後に置く

コメント