Графика контролируемого и неконтролируемого обучения в tikzpicture

Графика контролируемого и неконтролируемого обучения в tikzpicture

Я хотел бы представить эти два графика с помощью tikzpicture. Мне не нужно, чтобы они были соединены вместе, как показано ниже, но я хотел бы иметь что-то похожее.

введите описание изображения здесь

Я могу построить диаграмму рассеяния следующим образом:

введите описание изображения здесь

Где у меня есть два уникальных / различных кластера. Я хотел бы нарисовать линейно разделяемую линию, как в примере контролируемого обучения, а также нарисовать кластеры в примере неконтролируемого обучения.

Кроме того, было бы здорово иметь цвета/более крупные точки.

Код:

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
axis lines = left,
xlabel = x,
ylabel = y,
]
\addplot[only marks] table [%
x = x, 
y = y, 
col sep = comma]{
    x, y
    %cluster 1
    2, 3
    3, 5
    4, 5
    3, 8
    5, 9
    3, 2
    5, 6
    6, 6
    7, 9
    10, 4
    11, 5
    9, 4
    %cluser 2
    
    20, 10
    21, 12
    24, 12
    25, 13
    27, 14
    22, 13
    23, 15
    25, 10
    15, 14
 };
\end{axis}
\end{tikzpicture}
\end{document}

решение1

Вы могли бы использовать scatter/classesдля форматирования точек из двух кластеров по-разному, но проще просто разделить его на два \addplots. Чтобы задать форматирование, используйте eg \addplot [blue, only marks, mark=*, mark size=5] ..., которые, я думаю, в основном говорят сами за себя.

Для линии и окружностей это почти просто случай использования обычных команд TikZ. Просто обратите внимание, что по умолчанию, если вы делаете это \draw (x,y) ..внутри axisсреды xи yне находитесь в системе координат axis.Пока невы либо а) используете (axis cs:x,y), либо б) добавляете \pgfplotsset{compat=1.11}(или более высокий номер версии), в этом случае axis csон становится значением по умолчанию.

Обратите внимание, что circle[radius=2]внутри axisтребуется compat=1.11(я думаю), но радиус снова в координатах осей, поэтому в этом случае он станет эллипсом. Вместо этого вы можете определить координату внутри axisи нарисовать круг снаружи. Оба варианта продемонстрированы в коде ниже.

введите описание изображения здесь

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11} % <-- added
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
axis lines = left,
xlabel = $x$,
ylabel = $y$,
clip mode=individual % so things drawn by \draw and similar are not cut off
]
\addplot [blue, only marks, mark=*, mark size=5] table [%
x = x, 
y = y, 
col sep = comma]{
    x, y
    %cluster 1
    2, 3
    3, 5
    4, 5
    3, 8
    5, 9
    3, 2
    5, 6
    6, 6
    7, 9
    10, 4
    11, 5
    9, 4
    };
    
\addplot+[red, only marks, mark=*, mark size=5] table [%
x = x, 
y = y, 
col sep = comma]{
    x, y
    20, 10
    21, 12
    24, 12
    25, 13
    27, 14
    22, 13
    23, 15
    25, 10
    15, 14
 };
 
 % to be able to use axis coordinates with \draw directly you need
 % \pgfplotsset{compat=1.11} or a higher version
 % if that is not present, use (axis cs:4,14) instead of (4,14),
 % to specify that the values should be interpreted as axis coordinates
 \draw [dashed] (4,14) -- (25,2);
 
 % save a coordinate for use later
 \coordinate (c2) at (23,12);
 
 % the blue circle is drawn inside the axis environment, and in axis coordinates
 % hence it becomes an ellipse
 \draw [blue, dashed] (6,6) circle[radius=5]; 

\end{axis}

% the red circle is drawn outside the axis, so actually looks like a circle,
% but the radius has no relation to the axis coordinates
\draw [red, dashed] (c2) circle[radius=2cm];
\end{tikzpicture}
\end{document}

Две оси

Есть несколько методов для размещения двух графиков рядом друг с другом. Вы можете добавить два tikzpictures один сразу за другим, или вы можете иметь две axisсреды в одном и том же tikzpictureи расположить вторую с помощью \begin{axis}[at={(x,y)},.... Лично мне нравится groupplotсреда из groupplotsбиблиотеки, которая предназначена для создания сеток осей.

введите описание изображения здесь

\documentclass{article}
\usepackage{pgfplots}
\usepgfplotslibrary{groupplots}
\pgfplotsset{compat=1.11}
\begin{document}
\begin{tikzpicture}
\begin{groupplot}[
group style={
  group size=2 by 1,
  horizontal sep=1.5cm
  },
axis lines = left,
xlabel = $x$,
ylabel = $y$,
width=5cm, % <-- set size of axes
clip mode=individual, % to avoid \draws being cut off
title style={yshift=1mm, font=\bfseries\sffamily}
]

\nextgroupplot[title=Supervised learning]
\addplot [blue, only marks, mark=*, mark size=3] table [%
x = x, 
y = y, 
col sep = comma]{
    x, y
    %cluster 1
    2, 3
    3, 5
    4, 5
    3, 8
    5, 9
    3, 2
    5, 6
    6, 6
    7, 9
    10, 4
    11, 5
    9, 4
    };
    
\addplot+[red, only marks, mark=*, mark size=3] table [%
x = x, 
y = y, 
col sep = comma]{
    x, y
    20, 10
    21, 12
    24, 12
    25, 13
    27, 14
    22, 13
    23, 15
    25, 10
    15, 14
 };
 
 % to be able to use axis coordinates with \draw directly you need
 % \pgfplotsset{compat=1.11} or a higher version
 % if that is not present, use (axis cs:4,14) instead of (4,14),
 % to specify that the values should be interpreted as axis coordinates
 \draw [dashed] (4,14) -- (25,2);
 

 
\nextgroupplot[title=Unsupervised learning]
\addplot [blue, only marks, mark=*, mark size=3] table [%
x = x, 
y = y, 
col sep = comma]{
    x, y
    %cluster 1
    2, 3
    3, 5
    4, 5
    3, 8
    5, 9
    3, 2
    5, 6
    6, 6
    7, 9
    10, 4
    11, 5
    9, 4
    };
    
\addplot+[red, only marks, mark=*, mark size=3] table [%
x = x, 
y = y, 
col sep = comma]{
    x, y
    20, 10
    21, 12
    24, 12
    25, 13
    27, 14
    22, 13
    23, 15
    25, 10
    15, 14
 };
 

 % save a coordinate for use later
 \coordinate (c2) at (23,12);
 
 % the blue circle is drawn inside the axis environment, and in axis coordinates
 % hence it becomes an ellipse
 \draw [blue, dashed] (6,6) circle[radius=5]; 

\end{groupplot}

% the red circle is drawn outside the axis, so actually looks like a circle,
% but the radius has no relation to the axis coordinates
\draw [red, dashed] (c2) circle[radius=1cm];


\end{tikzpicture}
\end{document}

Связанный контент