Search code examples
plotlatextikz

Labeling a bar chart in Latex


I have the following bar Chart in Latex:

\begin{figure}
    \centering
    \begin{tikzpicture}
        \begin{axis}[
            ybar,
            symbolic x coords={CRITICAL, HIGH, MEDIUM, LOW},
            x tick label style={rotate=50, anchor=north east},
            ymin=0, 
            bar width=0.8cm,
            nodes near coords, 
            axis x line=bottom,
            axis y line=left,
            enlarge x limits=1,
            ylabel={Anzahl},
        ]
        \addplot[draw=black, fill=red] coordinates {(CRITICAL, 3)};
        \addplot[draw=black, fill=orange] coordinates {(HIGH, 17)};
        \addplot[draw=black, fill=yellow] coordinates {(MEDIUM, 33)};
        \addplot[draw=black, fill=blue] coordinates {(LOW, 54)};
        \end{axis}
    \end{tikzpicture}
    \caption{Severity from the difference between Grype/Snyk and Docker Scout}
    \label{balkendiagramm_grype_scout}
\end{figure}

I get this: enter image description here

I would like the text to be centered under the bar. Furthermore, HIGH should also be listed. The last LOW should also be removed. How can I do this?

A bar chart with thes 3 Requirements.


Solution

  • I think this will help you.

    \documentclass{article}
    \usepackage{graphicx} % Required for inserting images
    \usepackage{subcaption}% Offers an user interface to sub-captions.
    \usepackage{float}% Improves the interface for defining floating objects
    \usepackage{pgfplots}
    
    \pgfplotsset{compat=newest}
    
    \begin{document}
    
    \begin{figure}
    \centering
    \begin{tikzpicture}
        \begin{axis}[
            symbolic x coords={
                CRITICAL, 
                HIGH, 
                MEDIUM, 
                LOW},
            xtick={CRITICAL,HIGH,MEDIUM,LOW},
            x tick label style={rotate=50,anchor=east},
            bar width=0.8cm,
            nodes near coords, 
            nodes near coords align={vertical},
            axis x line=bottom,
            enlarge y limits=0.1,
            enlarge x limits=0.2,
            ybar=-0.8cm, % because of bar width=0.8cm
            ymin=0, 
            axis y line=left,
            ylabel={Anzahl},
        ]
        \addplot[draw=black, fill=red]    coordinates {(CRITICAL, 3)};
        \addplot[draw=black, fill=orange] coordinates {(HIGH, 17)};
        \addplot[draw=black, fill=yellow] coordinates {(MEDIUM, 33)};
        \addplot[draw=black, fill=blue]   coordinates {(LOW, 54)};
        \end{axis}
    \end{tikzpicture}
    \caption{Severity from the difference between Grype/Snyk and Docker Scout}
    \label{balkendiagramm_grype_scout}
    \end{figure}
    
    \end{document}
    

    Result