从 csv 文件绘制 4 个变量图

从 csv 文件绘制 4 个变量图

我有一个包含 4 列的 csv 文件,如下所示:

PQR 成本

6, 3, 1, 超级碗

6,2,2,SC

6、1、3、SC

5, 4, 1,

5, 3, 2,

5,2,3,DR

5,1,4,DR

4、5、1、DR

4,4,2,巴西

4, 3, 3, BR

前三列显示了三个变量(P、Q、R)之间数字(n)的所有可能划分。在此示例中(n=10),我并未显示所有可能的组合。最后一列显示了对于每个比率,哪种情况最佳(SC、BR 或 DR)。我绘制图表的想法是在 x 轴上使用 Q,在 y 轴上使用 R,并绘制 BR、SC 或 DR 最佳的区域。有专家可以帮帮我吗?我提供了最小示例的样本 csv 文件数据。

答案1

我仍然不知道这是否和你想象的一样。如果不是,请考虑画一张草图。

\documentclass[border=5mm]{standalone}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.17}
% Note commas in the header as well!
\pgfplotstableread[col sep=comma]{
P, Q, R, cost
6, 3, 1, SC
6, 2, 2, SC
6, 1, 3, SC
5, 4, 1, DR
5, 3, 2, BR
5, 2, 3, DR
5, 1, 4, DR
4, 5, 1, DR
4, 4, 2, BR
4, 3, 3, BR
}\MyData

% you'll have the data in a file, so do
% \pgfplotstableread[col sep=comma]{filename}
% instead of the above
\begin{document}
\begin{tikzpicture}
% define a few macros for convenience
\newcommand\AxisW{6cm} % width/height of axis
\newcommand\AxisXMin{0.5} % xmin/ymin
\newcommand\AxisRange{10} % range of axis, both x and y
\begin{axis}[
  % define how the different cases are drawn
  % all should have same mark and draw opacity,
  % but change the color as you prefer
  scatter/classes={
    SC={mark=square*, draw opacity=0, fill=blue},
    DR={mark=square*, draw opacity=0, fill=red},
    BR={mark=square*, draw opacity=0, fill=green}
 },
 % add labels for the axes
 xlabel=Q,
 ylabel=R,
 % set up the size of the axis
 scale only axis, % width/height applies to axis box alone, without labels
 width=\AxisW, height=\AxisW,
 % set up the range of the axes
 xmin=\AxisXMin, xmax=\AxisXMin+\AxisRange,
 ymin=\AxisXMin, ymax=\AxisXMin+\AxisRange,
 % calculate the mark size - divide by 2 because the size is half the width
 mark size={\AxisW/\AxisRange/2},
 % set legend entries in one row
 legend columns=-1,
 % move legend outside top of axis
 legend style={at={(0.5,1.02)}, anchor=south},
 % have ticks every 1 unit distance
 xtick distance=1,ytick distance=1,
 ] 

\addplot [
  scatter, % make a scatter plot
  only marks, % for some reason have to say that we only want markers
  scatter src=explicit symbolic % say that the variable that declares which scatter class a point belongs to is explicitly given in the data stream, and is not a number, so should not be parsed as a number
  ]
  table[x=Q, % use Q-column for x-values
        y=R, % use R-column for y-values
        meta=cost % use cost-column to define which scatter class should be used
        ] \MyData;

\legend{SC, DR, BR}
\end{axis}
\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容