如何向 tikz 条形图添加车道

如何向 tikz 条形图添加车道
\documentclass[border=5mm] {standalone}
\usepackage{pgfplots, pgfplotstable}


\begin{document}

\pgfplotstableread[col sep=comma]{
activity,start,end
$a1$,12,19
$b1$,25,32
$d1$,26,33
$e1$,35,40
$h1$,50,54
$a2$,17,23
$d2$,28,32
$c2$,30,38
$e2$,50,59
$g2$,70,73
$a3$,25,30
$c3$,32,35
$d3$,35,40
$e3$,45,50
$f3$,50,55
$b3$,60,65
$d3$,62,67
$e3$,80,87
$g3$,90,98
}\loadedtable

\begin{tikzpicture}
\begin{axis}[
  nodes near coords xbar stacked configuration/.style={},
  nodes near coords style={font=\footnotesize},
  xbar stacked,
  xmin=5,
  xmax=105,
  bar width=0.2cm,
  axis lines=left,
  grid=both,
  major grid style={line width=.2pt,draw=gray!50},
  xlabel={time},
  width=\textwidth, height=7cm,
  enlarge y limits={abs=0.5},
  ytick=\empty,
]

\addplot [draw=none, forget plot] table [col sep=comma,x=start, y expr=-\coordindex]{\loadedtable};
\addplot [fill=black,
   nodes near coords,
   nodes near coords align={anchor=west},
   point meta=explicit symbolic] table[col sep=comma,x expr=\thisrow{end}-\thisrow{start}, y expr=-\coordindex,meta=activity]{\loadedtable};
\end{axis}
\end{tikzpicture}

\end{document}

上述代码生成以下 tikz 条形图:

tikz 中的条形图

我需要向图表中添加带有标签的通道,结果如下: tikz 中的带车道的条形图

答案1

通过添加一些“空”条形图并使用额外的刻度,我创建了车道,但我不知道如何集中车道名称

空条形图由

,0,0

额外的刻度由

  extra y ticks = {-5,-11,-21},
    extra y tick labels={Case 1, Case 2, Case 3},
    extra y tick style={grid=major,major grid style={thick,draw=black}, dashed, draw=black, tick label style={yshift=.5cm}}

完整代码如下:

\documentclass[border=5mm] {standalone}
\usepackage{pgfplots, pgfplotstable}


\begin{document}

\pgfplotstableread[col sep=comma]{
activity,start,end
$a1$,12,19
$b1$,25,32
$d1$,26,33
$e1$,35,40
$h1$,50,54
,0,0
$a2$,17,23
$d2$,28,32
$c2$,30,38
$e2$,50,59
$g2$,70,73
,0,0
$a3$,25,30
$c3$,32,35
$d3$,35,40
$e3$,45,50
$f3$,50,55
$b3$,60,65
$d3$,62,67
$e3$,80,87
$g3$,90,98
,0,0
}\loadedtable

\begin{tikzpicture}
\begin{axis}[
  nodes near coords xbar stacked configuration/.style={},
  nodes near coords style={font=\footnotesize},
  xbar stacked,
  xmin=5,
  xmax=105,
  ymin=-21,
  bar width=0.2cm,
  axis lines=left,
  grid=both,
  major grid style={line width=.2pt,draw=gray!70},
  xlabel={time},
  width=\textwidth, height=7cm,
  enlarge y limits={abs=0.5},
  ytick=\empty,
  extra y ticks = {-5,-11,-21},
    extra y tick labels={Case 1, Case 2, Case 3},
    extra y tick style={grid=major,major grid style={thick,draw=black}, dashed, draw=black, tick label style={yshift=.5cm}}
]

\addplot [draw=none, forget plot] table [col sep=comma,x=start, y expr=-\coordindex]{\loadedtable};
\addplot [fill=black,
   nodes near coords,
   nodes near coords align={anchor=west},
   point meta=explicit symbolic] table[col sep=comma,x expr=\thisrow{end}-\thisrow{start}, y expr=-\coordindex,meta=activity]{\loadedtable};
\end{axis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

相关内容