Marco
Marco

Reputation: 2807

How to properly set a range for second y-scale in ggplot2?

I found several threads containing the sec.axis in scale_y_continuous. I saw lots of formulas to transform the second scale. But I don't need trans=~./50 or trans=~.+50. I would prefer to set a manuel range. I don't see a reason why I should relate the second scale by formula to the first one. It's independent from it.

# data generation
x = seq(1:20)
y1 = runif(20, 5, 50000)
y2 = rnorm(20)
df1 = data.frame(x, y1)
df2 = data.frame(x, y2)

ggplot(data=df1, aes(x, y=y1, col="red")) +
  geom_line() +
  geom_point(data=df2, aes(x, y=y2, col="blue")) +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
  scale_y_continuous(breaks = scales::pretty_breaks(n = 10), sec.axis = sec_axis(trans=~., name="y2")) + 
  theme(legend.position="none")

enter image description here

When I run a single point command it gives the "natural" scale.

ggplot() +
  geom_point(data=df2, aes(x, y=y2)) 

enter image description here

How can I get the normal y scale from the second picture as a second y scale on the right side of the first graph?

Insight: There is no way to not relate the two y-axes.

ggplot(data=df1, aes(x, y=y1, col="red")) +
  geom_line() +
  geom_point(data=df2, aes(x, y=y2, col="blue")) +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
  scale_y_continuous(breaks = scales::pretty_breaks(n = 10), sec.axis = sec_axis(trans=~./50000, name="y2")) + 
  theme(legend.position="none")

enter image description here

Still: Why does the data points not align in line with the transformed second y-axis?

Upvotes: 1

Views: 168

Answers (1)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

I think you still need to work it out:

ggplot(data=df1, aes(x, y=y1, col="red")) +
  geom_line() +
  geom_point(data=df2, aes(x, y=(2.5+y2)*8000, col="blue")) +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
  scale_y_continuous(breaks = scales::pretty_breaks(n = 10), 
                     sec.axis = sec_axis(trans=~(./8000 - 2.5), name="y2")) + 
  theme(legend.position="none")

enter image description here

Upvotes: 1

Related Questions