![如何根據資料類型列為散點著色並建立圖例條目](https://rvso.com/image/298793/%E5%A6%82%E4%BD%95%E6%A0%B9%E6%93%9A%E8%B3%87%E6%96%99%E9%A1%9E%E5%9E%8B%E5%88%97%E7%82%BA%E6%95%A3%E9%BB%9E%E8%91%97%E8%89%B2%E4%B8%A6%E5%BB%BA%E7%AB%8B%E5%9C%96%E4%BE%8B%E6%A2%9D%E7%9B%AE.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}
它產生了這個圖(請注意,隨著第三個資料列的引入,程式碼將其玩具從嬰兒車中扔了出來,並且弄亂了(1,10) 和(2,25) 座標的繪製) :
我如何能:
- 根據每個散點的「類型」列,為每個散點著色,或為每個散點分配一個隨機符號。我意識到後者可能需要一個「if type=type1,symbol=triangle」類型語句,這是可以的。
- 建立圖例以指示哪種顏色屬於哪種資料類型
\addplot
我可以使用針對每種資料類型的單獨命令手動執行此操作\addlegendentry{type1}
,但肯定有一種簡單的方法可以使用單一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}