Balkendiagramm Formatierung

Tabellen und Grafiken erstellen und anordnen


olko
Forum-Newbie
Forum-Newbie
Beiträge: 6
Registriert: Mi 5. Nov 2025, 13:09

Balkendiagramm Formatierung

Beitrag von olko »

Ich habe bei dem folgenden Diagramm das Problem, dass links und rechts Nullen auftauchen. Mir ist auch klar wieso. Lasse ich die Dummies weg, dann sind die Balken abgeschnitten oder die Beschriftung ist verrutscht. Ich hoffe, dass jemand eine Lösung hat.
\begin{center}
\begin{tikzpicture}
  \begin{axis}[
    title={Notenverteilung in einer Klasse},
    ybar,
    bar width=15pt,
    ymin=0,
    ymax=10,
    width=13cm,
    height=6cm,
    symbolic x coords={Xleft, A, B, C, D, E, F, Xright},
    xtick=data,
    xticklabels={, A, B, C, D, E, F, }, % Dummy-Beschriftungen leer
    ylabel={Anzahl},
    axis lines=left,
    grid=major,
    major grid style={gray!30},
    nodes near coords,
    every node near coord/.append style={
      font=\small,
      color=blue
    },
    % Nullen weiß färben – Trick!
    every node near coord/.append style={
      /pgfplots/point meta post/.code={
        \pgfmathparse{\pgfplotspointmeta==0 ? "white" : "blue"}
        \edef\tempcolor{\pgfmathresult}
        \tikzset{every node near coord/.style={font=\small, color=\tempcolor}}
      }
    }
  ]

  \addplot+[
    draw=blue!80!black,
    fill=blue!30
  ] coordinates {
    (Xleft,0) (A,2) (B,5) (C,9) (D,7) (E,3) (F,1) (Xright,0)
  };

  \end{axis}
\end{tikzpicture}
\end{center}
O olko O

Benutzeravatar
Stefan Kottwitz
Admin
Admin
Beiträge: 2828
Registriert: Di 8. Jul 2008, 00:39
Kontaktdaten:

Re: Balkendiagramm Formatierung

Beitrag von Stefan Kottwitz »

Hallo Olko,

Du kannst einfach einen separaten zweiten Plot ergänzen für die dummy-Einträge, und diesen ohne nodes near coords machen:
\documentclass[tikz,border=10pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    title={Notenverteilung in einer Klasse},
    ybar,
    bar width=15pt,
    ymin=0,
    ymax=10,
    width=13cm,
    height=6cm,
    symbolic x coords={Xleft, A, B, C, D, E, F, Xright},
    xtick=data,
    xticklabels={, A, B, C, D, E, F, }, % Dummy-Beschriftungen leer
    ylabel={Anzahl},
    axis lines=left,
    grid=major,
    major grid style={gray!30},
    every node near coord/.append style={
      font=\small,
      color=blue
    },
  ]
  \addplot+[
    draw=blue!80!black,
    fill=blue!30,
    nodes near coords,
  ] coordinates {
   (A,2) (B,5) (C,9) (D,7) (E,3) (F,1)
  };
  \addplot+[
    draw=none,
    fill=none,
  ] coordinates {
    (Xleft,0) (Xright,0)
  };
  \end{axis}
\end{tikzpicture}
\end{document}

Antworten