如何在ggplot2中调整次要Y轴的间距或边距?

4

我正在使用以下代码在R中制作ggplot:

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())

并且这是输出结果:

enter image description here

问题是次要轴上的文本和刻度看起来非常拥挤。如何使两个y轴标签之间的刻度和轴标签间距相同?谢谢。

编辑:

这里是可重现的数据:

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


5
你能否更新一个可复制的样本?顺便说一下,你可以尝试添加以下内容:+ theme(axis.title.y= element_text(margin = margin(t = 0, r = 10, b = 0, l = 0))) + theme(axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 10))) - Mohanasundaram
1
不是针对你的问题的答案,但你应该考虑一种数据的替代呈现方式:https://blog.datawrapper.de/dualaxis/ - Phil
3
仅使用theme(axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 10))的后半部分就可以了,这样效果非常好。第一部分只是添加了主 y 轴的间距,所以我没有加上它。奇怪的是为什么主标签似乎预先设置了更多的空间,但这是一个很好的修复方法,谢谢! - Marco Pastor Mayo
1个回答

3

我有同样的问题,使用其第二部分解决了问题。

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

对我有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接