![データ型列に基づいて散布点に色を付け、凡例エントリを作成する方法](https://rvso.com/image/298793/%E3%83%87%E3%83%BC%E3%82%BF%E5%9E%8B%E5%88%97%E3%81%AB%E5%9F%BA%E3%81%A5%E3%81%84%E3%81%A6%E6%95%A3%E5%B8%83%E7%82%B9%E3%81%AB%E8%89%B2%E3%82%92%E4%BB%98%E3%81%91%E3%80%81%E5%87%A1%E4%BE%8B%E3%82%A8%E3%83%B3%E3%83%88%E3%83%AA%E3%82%92%E4%BD%9C%E6%88%90%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95.png)
次のようなファイルがあるとします。
\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) 座標のプロットが台無しになっていることに注意してください)。
どうすればいいですか:
- 各散布点に色を付ける、または「type」列に基づいて各点にランダムなシンボルを割り当てることもできます。後者にはおそらく「if type=type1, symbol=triangle」タイプのステートメントが必要になると思いますが、これは問題ありません。
- どの色がどのデータ型に属しているかを示す凡例を作成します。
\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}