我有这个条形图,我想做三件事:
- 删除条形图中的数字,它们是重叠的(如果可能的话只保留一个,象征着两个条形图具有相同的值);
- 在图例的框架内输入“数据大小”,然后输入10KB和20KB的值;
- 将 y 轴值更改为 28
我正在使用的代码:
\begin{tikzpicture}
\begin{axis}[
ybar,
enlargelimits=0.3,
legend style={at={(0.5 ,-0.20)},
anchor=north,legend columns =-1},
ylabel ={Memory Usage (KB)},
xlabel ={Transmissions},
symbolic x coords ={10,100,250},
xtick=data,
nodes near coords ,
nodes near coords align ={vertical},
]
\addplot coordinates {(10,25.4) (100,25.4) (250,25.4)};
\addplot coordinates {(10,25.4) (100,25.4) (250,25.4)};
\legend{10KB,20KB}
\end{axis}
\end{tikzpicture}
我的图表是这样的:
答案1
\documentclass[border = 5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ymin = 0, ymax = 28,
ybar,
enlarge x limits=0.3,
legend style={at={(0.5 ,-0.20)},
anchor=north,legend columns =-1},
ylabel ={Memory Usage (KB)},
xlabel ={Transmissions},
symbolic x coords ={10,100,250},
xtick=data,
nodes near coords align ={vertical},
]
\addlegendimage{empty legend}
\addplot[nodes near coords, fill = blue!30] coordinates {(10,25.4) (100,25.4) (250,25.4)};
\addplot coordinates {(10,25.4) (100,25.4) (250,25.4)};
\addlegendentry{Data Size}
\addlegendentry{100KB}
\addlegendentry{20KB}
%\legend{10KB,20KB}
\end{axis}
\end{tikzpicture}
\end{document}
消除
nodes near coords
使用
\addlegendentry{Data Size}
设置限制
ymax
答案2
这只是对 caverac 的精彩回答的一个小补充,展示了如何将两者合并nodes near coords
为一。
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\newcounter{mynodeindex}
\pgfplotsset{%based on https://tex.stackexchange.com/a/75811/121799
step nodeindex/.code={\stepcounter{mynodeindex}},
name nodes near coords/.style={
every node near coord/.append style={/pgfplots/step nodeindex,
name=#1-\themynodeindex,
alias=#1-last,
},
},
name nodes near coords/.default=coordnode
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
enlargelimits=0.3,
legend style={at={(0.5 ,-0.20)},
anchor=north,legend columns =-1},
ylabel ={Memory Usage (KB)},
xlabel ={Transmissions},
symbolic x coords ={10,100,250},
xtick=data,
nodes near coords={},
nodes near coords align ={vertical},
name nodes near coords
]
\addplot coordinates {(10,28) (100,28) (250,28)};
\addplot coordinates {(10,28) (100,28) (250,28)};
\legend{10KB,20KB}
\end{axis}
\pgfmathtruncatemacro{\Xmax}{\themynodeindex/2}
\foreach \X [evaluate=\X as \Y using {int(\X+\Xmax)}] in {1,...,\Xmax}
{\path (coordnode-\X) -- (coordnode-\Y) node[midway,yshift=2pt] {28};}
\end{tikzpicture}
\end{document}