Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust spacing or margin for secondary Y axis on ggplot2?

I am working on a ggplot in R with the following code:

s=40
ggplot(data = NULL) +
  geom_line(data = stk, aes(x = date, y = price)) +
  geom_line(data = gdp, aes(x = year, y = gdp1*s)) +
  scale_y_continuous("Index of Total Stock Price",
                     sec.axis = sec_axis(~. /s, name = "Real GDP (trillions of USD in 2012)"),
                     limits = c(0, 100)) +
  scale_x_date(breaks = seq(from = as.Date("1900-01-01"),
                            to = as.Date("1945-01-01"),
                            by = "5 years"),
               labels=date_format("%Y")) +
  xlab(element_blank())

And this output:

enter image description here

The problem is that the text and ticks in the secondary axis look very cramped up. How can I make the space between the ticks and the axis label be the same for both y axis labels? Thanks.

EDIT:

Here is reproducible data:

set.seed(1000)
df1 <- data.frame(y1=rnorm(100, 0, 1),
                  x=seq(1, 100, 1))
df2 <- data.frame(y2=rnorm(100, 0, 1),
                  x=seq(1, 100, 1))
ggplot(data = NULL) +
  geom_line(data = df1, aes(x = x, y = y1)) +
  geom_line(data = df2, aes(x = x, y = y2*2)) +
  scale_y_continuous("Label of Primary Y Axis",
                     sec.axis = sec_axis(~. *2, name = "Label of Secondary Y Axis"))

enter image description here

like image 845
Marco Pastor Mayo Avatar asked Oct 14 '25 07:10

Marco Pastor Mayo


1 Answers

I had the same problem, using the second part of that,

theme(axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 10))

worked for me.

like image 128
Fabio Daniel Trinco Avatar answered Oct 17 '25 04:10

Fabio Daniel Trinco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!