How to plot two axis bar chart side by side
Update: An alternative approach with a minor modification of the code in OP:
- Reverse the columns in
q1
: i.e. useq1 = qq[[All, {2, 1}]];
, and - Use
BarSpacing -> {0, 1}
in both charts
q1 = qq[[All, {2, 1}]]; q2 = qq[[All, {1, 3}]];
qw1 = BarChart[q1, BarSpacing -> {0, 1}, Frame -> {Left},
ChartStyle -> Darker[Red], FrameStyle -> Darker[Red],
ImagePadding -> 30, ImageSize -> 500, ImageMargins -> 4];
qw2 = BarChart[q2, BarSpacing -> {0, 1}, Frame -> {Right},
FrameTicks -> All, ChartStyle -> Darker[Blue],
FrameStyle -> Darker[Blue], ImageMargins -> 4,
ImagePadding -> 30,
ImageSize -> 500];
Overlay[{qw1, qw2}]
Use BarSpacing -> {-.5, 1}
in both charts to get:
Original answer:
You can use the function modifiedrange
from this answer to rescale the second data set and use Charting`FindTicks
to relabel the ticks on the right frame:
ClearAll[modifiedrange]
modifiedrange[{{a_, b_}, {c_, d_}}, z_: 0] /; z <= d := {(a d - (a - b + d) z)/(b - z), d}
{data1, data2} = Transpose[qq[[All, {2, 3}]]] ;
data2b = Rescale[data2, modifiedrange[MinMax /@ {data1, data2}], MinMax @ data1];
tickF = Charting`FindTicks[MinMax@data1, modifiedrange[MinMax /@ {data1, data2}]];
BarChart[Transpose[{data1, data2b}],
ChartStyle -> (Darker /@ {Red, Blue}),
BarSpacing -> {0, 1},
ImageSize -> 500,
Axes -> {True, False},
Frame -> {Left, Right},
FrameStyle -> { Darker /@ {Red, Blue}, {Automatic, Automatic}},
FrameTicks -> {{Automatic, tickF}, {Automatic, Automatic}}]
Use BarSpacing -> {-.5, 1}
to get
You can use ChartElementFunction
to manually nudge the bars over by a bit, the following for example moves them 0.5 to the right:
ChartElementFunction -> (Rectangle @@ Transpose[# + {0.5, 0}] &)
For the combining part, you can search this site for ways to overlay charts cleanly (e.g. this question). One way is to use the CombinePlots
function from the ForScience`
1 paclet:
<<ForScience`
qq = {{a, .261, 93}, {b, .247, 136}, {c, .311, 70}, {d, .336,
80}, {e, .339, 71}, {f, .337, 60}};
q1 = qq[[All, {1, 2}]]; q2 = qq[[All, {1, 3}]]
qw1 = BarChart[
q1,
BarSpacing -> {0, 1},
Frame -> Left,
ChartStyle -> Darker[Red],
FrameStyle -> Darker[Red],
ImagePadding -> 30,
ImageSize -> 500,
ImageMargins -> 4
]
qw2 = BarChart[
q2,
BarSpacing -> {0, 1},
Frame -> Left,
ChartStyle -> Darker[Blue],
FrameStyle -> Darker[Blue],
ImageMargins -> 4,
ImagePadding -> 30,
ImageSize -> 500,
ChartElementFunction -> (Rectangle @@ Transpose[# + {0.5, 0}] &)
]
CombinePlots[
qw1, qw2,
"AxesSides" -> "TwoY", (* move the second plot to the right axis *)
PlotRange -> All, (* ensure that all the bars are shown *)
Frame -> {Left, Right}
]
1You can install the current version using
PacletInstall["https://github.com/MMA-ForScience/ForScience/releases/download/v0.88.45/ForScience-0.88.45.paclet"]