如何根據資料類型列為散點著色並建立圖例條目

如何根據資料類型列為散點著色並建立圖例條目

假設我有一個這樣的文件:

\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) 座標的繪製) :

在此輸入影像描述

我如何能:

  1. 根據每個散點的「類型」列,為每個散點著色,或為每個散點分配一個隨機符號。我意識到後者可能需要一個「if type=type1,symbol=triangle」類型語句,這是可以的。
  2. 建立圖例以指示哪種顏色屬於哪種資料類型

\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}

相關內容