0

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

Mofi
  • 46,139
  • 17
  • 80
  • 143
Salah Uddin
  • 25
  • 1
  • 7

1 Answers1

2

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

j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • Thanks a lot. But, if I set 0 for C instead of 3 then the blue bar and the red bar is not starting from the x-axis. Can you please help me with how I can fix this? – Salah Uddin Mar 26 '21 at 04:57
  • Try putting `ymin=0` to both axes, e.g., `ylabel=axis1, ymin=0,`. – j1-lee Mar 26 '21 at 05:03