![在堆叠条形图中放置标签并自定义图例](https://linux22.com/image/478423/%E5%9C%A8%E5%A0%86%E5%8F%A0%E6%9D%A1%E5%BD%A2%E5%9B%BE%E4%B8%AD%E6%94%BE%E7%BD%AE%E6%A0%87%E7%AD%BE%E5%B9%B6%E8%87%AA%E5%AE%9A%E4%B9%89%E5%9B%BE%E4%BE%8B.png)
我必须创建一个水平堆叠条形图。但我需要将百分比放在条形图内,并将自定义图例放在图形旁边。
这是我在 Latex 中的代码:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.8}
\begin{tikzpicture}
\begin{axis}[
xbar stacked,
bar width = 25pt,
xmin = -1,
xmax = 101,
symbolic y coords={C, C++, Java, JavaScript, PHP, Python, Ruby},
x tick label style={font=\small},
xticklabels = {,,},
]
\addplot+[xbar, blue!50!green, thick, fill=white] plot coordinates
{(91,C) (87,C++) (72,Java) (91,JavaScript) (93,PHP) (91,Python) (87,Ruby)};
\addplot+[xbar, red, thick, fill=white] plot coordinates
{(9,C) (13,C++) (28,Java) (9,JavaScript) (7,PHP) (9,Python) (13,Ruby)};
\end{axis}
\end{tikzpicture}
\end{document}
代码仅显示堆叠条形图,而没有条形图内的标签,我需要在图表旁边添加图例。这是我想要看到的图表:
任何帮助,将不胜感激。
答案1
我尝试了一下,找到了一个办法。我使用 坐标附近的节点 来表示条形内的百分比。此外,我使用\addlegendimage
和\addlegendentry
来表示图表旁边的图例。我还将其更改compat=
为1.9
。
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.9}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xbar stacked,
bar width = 25pt,
xmin = -1,
xmax = 101,
symbolic y coords={C, C++, Java, JavaScript, PHP, Python, Ruby},
x tick label style={font=\small},
xticklabels = {,,},
legend style={at={(1.05,0.6)},anchor=north west, draw=none},
nodes near coords,
every node near coord/.append style={font=\footnotesize},
point meta = explicit symbolic
]
\addlegendimage{empty legend},
\addplot+[xbar, blue!50!green, thick, fill=white] plot coordinates
{(91,C)[91]
(87,C++)[87]
(72,Java)[72]
(91,JavaScript)[91]
(93,PHP)[93]
(91,Python)[91]
(87,Ruby)[87]};
\addplot+[xbar, red, thick, fill=white] plot coordinates
{(9,C)[9]
(13,C++)[13]
(28,Java)[28]
(9,JavaScript)[9]
(7,PHP)[7]
(9,Python)[9]
(13,Ruby)[13]};
\addlegendentry{\hspace{-.6cm}\textbf\small{Type}},
\addlegendentry{Seed},
\addlegendentry{No seed},
\end{axis}
\end{tikzpicture}
\end{document}