1

I was wondering if it's possible to get a two sided barplot (e.g. Two sided bar plot ordered by date) that shows above Data A and below Data B of each X-Value.

Data A would be for example the age of a person and Data B the size of the same person. The problem with this and the main difference to the examples above: A and B have obviously totally different units/ylims.

Example:

X = c("Anna","Manuel","Laura","Jeanne") # Name of the Person
A = c(12,18,22,10)     # Age in years
B = c(112,186,165,120) # Size in cm 

Any ideas how to solve this? I don't mind a horizontal or a vertical solution.

Thank you very much!

Community
  • 1
  • 1
Frosi
  • 177
  • 5
  • 12

1 Answers1

3

Here's code that gets you a solid draft of what I think you want using barplot from base R. I'm just making one series negative for the plotting, then manually setting the labels in axis to reference the original (positive) values. You have to make a choice about how to scale the two series so the comparison is still informative. I did that here by dividing height in cm by 10, which produces a range similar to the range for years.

# plot the first series, but manually set the range of the y-axis to set up the
# plotting of the other series. Set axes = FALSE so you can get the y-axis
# with labels you want in a later step.
barplot(A, ylim = c(-25, 25), axes = FALSE)

# plot the second series, making whatever transformations you need as you go. Use
# add = TRUE to add it to the first plot; use names.arg to get X as labels; and
# repeat axes = FALSE so you don't get an axis here, either.
barplot(-B/10, add = TRUE, names.arg = X, axes = FALSE)

# add a line for the x-axis if you want one
abline(h = 0)

# now add a y-axis with labels that makes sense. I set lwd = 0 so you just
# get the labels, no line.
axis(2, lwd = 0, tick = FALSE, at = seq(-20,20,5),
     labels = c(rev(seq(0,200,50)), seq(5,20,5)), las = 2)

# now add y-axis labels
mtext("age (years)", 2, line = 3, at = 12.5)
mtext("height (cm)", 2, line = 3, at = -12.5)

Result with par(mai = c(0.5, 1, 0.25, 0.25)):

enter image description here

ulfelder
  • 5,305
  • 1
  • 22
  • 40