在堆叠条形图中放置标签并自定义图例

在堆叠条形图中放置标签并自定义图例

我必须创建一个水平堆叠条形图。但我需要将百分比放在条形图内,并将自定义图例放在图形旁边。

这是我在 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}

在此处输入图片描述 我对此还很陌生,所以我的编码可能有点平凡。希望这能有所帮助。祝一切顺利!

相关内容