Одинарная столбчатая диаграмма, значения и легенда

Одинарная столбчатая диаграмма, значения и легенда
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\pgfplotsset{testbar/.style={
title=strookdiagram sporten,
xbar stacked,
width=10cm,
axis y line*= none, axis x line*= bottom,
xmajorgrids = true,
xmin=0,xmax=100,
ytick = data,
yticklabels = {},
tick align = outside, xtick pos = left,
bar width=6mm, y=8mm,
enlarge y limits={abs=0.625},% 0.5 + 0.5*(y - bar width)/y [TeX.sx #47995]
nodes near coords,
nodes near coords align={left},
}}
\begin{tikzpicture}
\begin{axis}[testbar] 
    \addplot[fill=red!40] coordinates{(20,0) };
    \addplot[fill=gray!40] coordinates{(10,0)};
    \addplot[fill=green!40] coordinates{(20,0) };
    \addplot[fill=orange!40] coordinates{(40,0) };
    \addplot[fill=blue!40] coordinates{(3,0) };
    \addplot[fill=red!40] coordinates{(7,0) };
\end{axis}
\end{tikzpicture}
\end{document}

Я хотел сделать составную столбчатую диаграмму, горизонтальную, с легендой и процентом каждой части. Код выше дает мне:

тест сложенных стержней1

Но как видите, проценты все нулевые. Я тоже хочу легенду. Спасибо заранее.

РЕДАКТИРОВАТЬ

Я изменил код с помощью Джесси, и теперь мой код выглядит так:

 \documentclass{article}
 \usepackage{pgfplots}
 \usetikzlibrary{positioning}
 \begin{document}
 \pgfplotsset{testbar/.style={
 title=strookdiagram sporten,
 title style={yshift=10pt},
 xbar stacked, area style,
width=10cm,
axis y line*= none, axis x line*= bottom,
xmajorgrids = true,
xmin=0,
xmax=100,
x=1mm,
xtick={0,10,...,100},
ytick = data,
yticklabels = {},
tick align = outside, xtick pos = left,
bar width=6mm, y=8mm,
enlarge y limits={abs=0.625},% 0.5 + 0.5*(y - bar width)/y [TeX.sx #47995]
%nodes near coords,
nodes near coords={\pgfmathprintnumber\pgfplotspointmeta\%}
every node near coord/.append style={rotate=-90,font=\small, left,shift={(axis direction cs:-3,0)}}
}}
\begin{tikzpicture}
\begin{axis}[testbar,legend style={area legend, at={(0.5,-0.85)}, anchor=north, legend columns=-1}] 
\addplot[fill=red!40] coordinates{(20,0) };
\addplot[fill=gray!40] coordinates{(10,0)};
\addplot[fill=green!40] coordinates{(20,0) };
\addplot[fill=orange!40] coordinates{(40,0)};
\addplot[fill=blue!40] coordinates{(3,0) };
\addplot[fill=red!40] coordinates{(7,0) };
\legend{Voetbal,Netbal,C,D,E,F}
\end{axis}
\end{tikzpicture}
\end{document}

Но образ, который он мне сейчас дает,

версия 2

Я обновил все пакеты с помощью TeX Live Utilty, а мой редактор TeX — TeXpad.

решение1

Эта попытка пытается предоставить два решения. Поскольку стекирование означает добавление x- или y-координат последовательных \addplotкоманд друг на друга (здесь это направление x), вызывая перекрытие для 90% и 3% в частности.

Первое решение сверху — повернуть метку на -90 градусов и использовать маленький размер шрифта. Для этого нужно определить стиль добавления с помощью every node near coord/.append styleкоманды. Отмечено, что команда shift shift={(axis direction cs:-3,0)}— это переместить метки вверх, чтобы они не сталкивались с полями для лучшей читаемости.

Второй график внизу просто меняет координаты y с тех же y=0 на y=0,1,2,3,4,5, таким образом делая их похожими на лестницу, не меняя ориентацию меток по умолчанию. Кроме того, на этом графике вы увидите, почему метки накладываются друг на друга, если они сворачиваются в одну горизонтальную сложенную полосу.

Что касается легенды, стиль легенды определяется с помощью legend style={area legend, at={(0.5,-0.15)}, anchor=north, legend columns=-1}.

введите описание изображения здесь

\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{positioning}
\begin{document}
\pgfplotsset{testbar/.style={
title=strookdiagram sporten,
xbar stacked, area style,
width=10cm,
axis y line*= none, axis x line*= bottom,
xmajorgrids = true,
xmin=0,xmax=100,
ytick = data,
yticklabels = {},
tick align = outside, xtick pos = left,
bar width=6mm, y=8mm,
enlarge y limits={abs=0.625},% 0.5 + 0.5*(y - bar width)/y [TeX.sx #47995]
nodes near coords,
every node near coord/.append style={rotate=-90,font=\small, left,shift={(axis direction cs:-3,0)}}
}}
\begin{tikzpicture}
\begin{axis}[testbar,legend style={area legend, at={(0.5,-0.85)}, anchor=north, legend columns=-1}] 
    \addplot[fill=red!40] coordinates{(20,0) };
    \addplot[fill=gray!40] coordinates{(10,0)};
    \addplot[fill=green!40] coordinates{(20,0) };
    \addplot[fill=orange!40] coordinates{(40,0)};
    \addplot[fill=blue!40] coordinates{(3,0) };
    \addplot[fill=red!40] coordinates{(7,0) };
   \legend{A,B,C,D,E,F}
\end{axis}
\end{tikzpicture}

\vspace{1cm}

\pgfplotsset{testbar/.style={
title=strookdiagram sporten,
xbar stacked, area style,
width=10cm,
axis y line*= none, axis x line*= bottom,
xmajorgrids = true,
xmin=0,xmax=100,
ytick = data,
yticklabels = {},
tick align = outside, xtick pos = left,
bar width=6mm, y=8mm,
enlarge y limits={abs=0.625},% 0.5 + 0.5*(y - bar width)/y [TeX.sx #47995]
nodes near coords,
nodes near coords align={left}
}}
\begin{tikzpicture}
\begin{axis}[testbar,legend style={area legend, at={(0.5,-0.15)}, anchor=north, legend columns=-1}] 
    \addplot[fill=red!40] coordinates{(20,0)};
    \addplot[fill=gray!40] coordinates{(10,1)};
    \addplot[fill=green!40] coordinates{(20,2) };
    \addplot[fill=orange!40] coordinates{(40,3) };
    \addplot[fill=blue!40] coordinates{(3,4) };
    \addplot[fill=red!40] coordinates{(7,5) };
   \legend{A,B,C,D,E,F}
\end{axis}
\end{tikzpicture}
\end{document}

Редактировать:

  1. ОП предпочитает использовать проценты вместо чисел. Тогда замените соответствующие строки на nodes near coords={\pgfmathprintnumber\pgfplotspointmeta\%}.

  2. Чтобы переместить заголовок выше, добавьте title style={yshift=10pt}к оси первого графика, поскольку добавленный % будет конфликтовать с заголовком в старой настройке.

  3. Чтобы удалить сетку сверху, добавьте axis on top=falseкtestbar/.style

После внесения этих изменений новый результат показан ниже.

введите описание изображения здесь

Связанный контент