latextikzpgfplots

How to draw double y-axis barplot graph like this in pgfplot?


I used the table data below to draw the plot using Matplotlib.

name, value_axis1, value_axis2
A,    16,          299239.74
B,    18,          292816.67
C,     3,           72799.22
D,    10,          116248.54

Bar graph of the data


Solution

  • Use two \begin{axis} ... \end{axis} environments, one for the left and the other for the right. You can find the relevant part axis y line in the code below.

    To prevent the bars from being on top of each other, bar shift is used (and set to the half of the bar width so that the bars are glued together).

    \documentclass{article}
    \usepackage{pgfplots}
    \pgfplotsset{width=10cm,height=8cm,compat=1.16}
    
    \begin{document}
    \begin{tikzpicture}
      \begin{axis}[
        ybar,
        symbolic x coords={A,B,C,D},
        bar width=0.6cm, bar shift=-0.3cm,
        xtick=data,
        axis y line*=left,
        ylabel=axis1,
        xlabel=name,
        ]
        \addplot[draw=red,fill=red] coordinates {
            (A,16) (B,18) (C,3) (D,10)
          };
      \end{axis}
      \begin{axis}[
        ybar,
        symbolic x coords={A,B,C,D},
        bar width=0.6cm, bar shift=0.3cm,
        xtick=data,
        axis y line*=right,
        ylabel=axis2
        ]
        \addplot[draw=blue,fill=blue] coordinates {
            (A, 299239.74) (B, 292816.67) (C, 72799.22) (D, 116248.54)
          };
      \end{axis}
    \end{tikzpicture}
    \end{document}
    

    Bar plot with two y axes