如何以獨立於具體數據的靈活方式將像下面這樣的圖中的 y 軸從 0-max(此處為 0-3)重新標記為 0-1?例如,是否可以存取繪圖期間出現的最大 y 值並使用它來確定 y 標籤 1 的位置?
這個問題繼續討論如何在 LaTex 環境中繪製離散數的累積分佈函數 (CDF)?。
\documentclass[border=2mm]{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\makeatletter
\long\def\ifnodedefined#1#2#3{%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}%
}
\pgfplotsset{
discontinuous/.style={
scatter,
scatter/@pre marker code/.code={
\ifnodedefined{marker}{
\pgfpointdiff{\pgfpointanchor{marker}{center}}%
{\pgfpoint{0}{0}}%
\ifdim\pgf@y>0pt
\tikzset{options/.style={mark=*, fill=white}}
\draw [densely dashed,blue] (marker-|0,0) -- (0,0);
\draw plot [mark=*] coordinates {(marker-|0,0)};
\else
\tikzset{options/.style={mark=none}}
\fi
}{
\tikzset{options/.style={mark=none}}
}
\coordinate (marker) at (0,0);
\begin{scope}[options]
},
scatter/@post marker code/.code={\end{scope}}
}
}
\makeatother
\begin{document}
\begin{tikzpicture}
\begin{axis}[
clip=false,
jump mark left,
ymin=0,ymax=3.5,
xmin=14,xmax=35,
xlabel={income},
ylabel={cumulative distribution},
every axis plot/.style={very thick},
discontinuous,
table/create on use/cumulative distribution/.style={
create col/expr={\pgfmathaccuma + \thisrow{f(x)}}
}
]
\addplot [red] table [y=cumulative distribution]{
P(x) f(x)
14 0
15 1/5
18 2/5
25 3/5
31 4/5
33 1
35 0
};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
使用pgfplots:讀取數據,計算圖表您可以計算累積百分比,將其新增為額外列,然後繪製該列。
微量元素:
\documentclass[border=2mm]{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\makeatletter
\long\def\ifnodedefined#1#2#3{%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}%
}
\pgfplotsset{
discontinuous/.style={
scatter,
scatter/@pre marker code/.code={
\ifnodedefined{marker}{
\pgfpointdiff{\pgfpointanchor{marker}{center}}%
{\pgfpoint{0}{0}}%
\ifdim\pgf@y>0pt
\tikzset{options/.style={mark=*, fill=white}}
\draw [densely dashed,blue] (marker-|0,0) -- (0,0);
\draw plot [mark=*] coordinates {(marker-|0,0)};
\else
\tikzset{options/.style={mark=none}}
\fi
}{
\tikzset{options/.style={mark=none}}
}
\coordinate (marker) at (0,0);
\begin{scope}[options]
},
scatter/@post marker code/.code={\end{scope}}
}
}
\makeatother
\pgfplotstableread{
P(x) f(x)
14 0
15 1/5
18 2/5
25 3/5
31 4/5
33 1
35 0
}\datatable
% Calculate the sum of the y column
\pgfmathsetmacro\pgfplotstablesum{0}
\pgfplotstableforeachcolumnelement{f(x)}\of\datatable\as\yvalue{
\pgfmathsetmacro\pgfplotstablesum{\pgfplotstablesum+\yvalue}
}
% Define a "virtual column" that calculates the cumulative percentage on the fly
\pgfplotstableset{
create on use/cumulative percentage/.style={
create col/expr={\pgfmathaccuma + \thisrow{f(x)}/\pgfplotstablesum}
}
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
clip=false,
jump mark left,
ymin=0,ymax=1.0,
xmin=14,xmax=35,
xlabel={income},
ylabel={cumulative distribution},
every axis plot/.style={very thick},
discontinuous
]
\addplot [red] table [y=cumulative percentage]{\datatable};
\end{axis}
\end{tikzpicture}
\end{document}
結果: