データ型列に基づいて散布点に色を付け、凡例エントリを作成する方法

データ型列に基づいて散布点に色を付け、凡例エントリを作成する方法

次のようなファイルがあるとします。

\documentclass{standalone}
\usepackage{pgfplots,filecontents}
\begin{filecontents*}{data}
1 10 type1
2 25 type2
3 75 type2
4 100 type3
5 150 type3
\end{filecontents*}

\begin{document}  

\begin{tikzpicture}
    \begin{axis}   
    \addplot[scatter,only marks] 
        table[row sep=crcr] {data};         
    \end{axis}
\end{tikzpicture}

\end{document}

これにより、次のプロットが生成されます (3 番目のデータ列の導入によりコードがおかしくなり、(1,10) および (2,25) 座標のプロットが台無しになっていることに注意してください)。

ここに画像の説明を入力してください

どうすればいいですか:

  1. 各散布点に色を付ける、または「type」列に基づいて各点にランダムなシンボルを割り当てることもできます。後者にはおそらく「if type=type1, symbol=triangle」タイプのステートメントが必要になると思いますが、これは問題ありません。
  2. どの色がどのデータ型に属しているかを示す凡例を作成します。

\addplot各データ型の個別のコマンドに続いてを手動で実行することもできます\addlegendentry{type1}が、 を 1 つ使用してこれを自動化する簡単な方法があるはずですaddplot

答え1

PGFPLOTSマニュアルには、まさにあなたが望んでいることを実行する例があります。現在は107ページにあります。4.5.11 散布図

\documentclass[border=9,tikz]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[legend pos=south east]
    \addplot[
        scatter,only marks,scatter src=explicit symbolic,
        scatter/classes={
            a={mark=square*,blue},
            b={mark=triangle*,red},
            c={mark=o,draw=black,fill=black}
        }
    ]
    table[x=x,y=y,meta=label]{
        x    y    label
        0.1  0.15 a
        0.45 0.27 c
        0.02 0.17 a
        0.06 0.1  a
        0.9  0.5  b
        0.5  0.3  c
        0.85 0.52 b
        0.12 0.05 a
        0.73 0.45 b
        0.53 0.25 c
        0.76 0.5  b
        0.55 0.32 c
    };
    \legend{Class 1,Class 2,Class 3}
\end{axis}
\end{tikzpicture}
\end{document}

関連情報