2

I have found multiple ways to create a secondary y-axis in plot but I couldn't find a way to create a secondary y-axis in histogram.

Here is a sample code:

a <- sample(90:110, 50, replace=TRUE)
b <- runif(50, min=0, max=1)
hist(a)
lines(b)

b is too small to show in hist(a) so is there any way that I can see both in the histogram?

Y. Z.
  • 369
  • 2
  • 16
  • 1
    I have no idea what you intend to show here. Are you expecting the random values in `b` (`U~[0,1]`) to somehow map intuitively on an x-axis ranging from 90-110 or a y-axis mapping from 0 to something around 14? Perhaps you need something like `par(new=TRUE)` and overlaying a new plot on the old. (Hint: this is a bit too vague, please provide clarity in the form of your expected output.) – r2evans Mar 07 '18 at 08:43
  • 1
    Not completely true, @RolandASc, try `lines(c(rep(0,90),5,10,5))` after the `hist` above. If a single vector, it assumes that the vector is `y` and `x=seq_along(y)`. – r2evans Mar 07 '18 at 08:54
  • @r2evans, thank you for your clarification. My goal is adding a guiding line b on the histogram(a). Since the value of b is too small so I need to create a second y-axis for the b. – Y. Z. Mar 07 '18 at 15:34
  • I'm not certain what a guiding line is, do you mean to connect the top of each histogram bar? Or a line describing some other (extrinsic, here) property of the data? How do you relate `b` to `a`? – r2evans Mar 07 '18 at 15:48

1 Answers1

1

Technically a solution may be quite an identical to the approach proposed for the plots in this answer. The idea is to use overlapping of two plots as proposed by @r2evans.

It makes sense to use color coding:

# set color rules
col_a <- "red"
col_b <- "darkblue"
col_common <- "black"

Then let's draw the histogram and the plot:

# draw a histogram first
par(mar = c(5, 5, 5, 5) + 0.3)
hist(a, col = col_a, axes = FALSE, xlab = "", ylab = "", main = "")
# add both axes with the labels
axis(side = 1, xlim = seq(along.with = b), col = col_a, col.axis = col_a)
mtext(side = 1, text = "a_value", col = col_a, line = 2.5)
axis(side = 2, col = col_a, col.axis = col_a, ylab = "")
mtext(side = 2, text = "a_Frequency", col = col_a, line = 2.5)
# ... and add an overlaying plot
par(new=TRUE)
plot(b, ylim = c(0, 1), axes = FALSE, col = col_b, type = "l", xlab = "", ylab = "")
points(b, col = col_b, pch = 20, xlab = "", ylab = "")
axis(side = 3, xlim = seq(along.with = b), col = col_b, col.axis = col_b)
mtext(side = 3, text = "b_index", col = col_b, line = 2.5)
axis(side = 4, ylim = c(0, 1), col = col_b, col.axis = col_b)
mtext(side = 4, text = "b_value", col = col_b, line = 2.5)
box(col = col_common)
Ekatef
  • 1,061
  • 1
  • 9
  • 12