【问题标题】:How to adjust spacing or margin for secondary Y axis on ggplot2?如何在 ggplot2 上调整辅助 Y 轴的间距或边距?
【发布时间】:2020-09-02 13:22:01
【问题描述】:

我正在使用以下代码在 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())

这个输出:

问题是辅助轴上的文本和刻度看起来非常狭窄。如何使两个 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"))

【问题讨论】:

  • 你能更新一个可重现的样本吗?顺便说一句,您可以尝试添加,+主题(axis.title.y= element_text(margin = margin(t = 0,r = 10,b = 0,l = 0)))+主题(axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 10)))
  • 不是您问题的答案,但您应该考虑使用此数据的另一种表示形式:blog.datawrapper.de/dualaxis
  • 只使用第二部分theme(axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 10)),效果很好。第一部分只是简单地在主 y 轴上添加了空间,所以我没有放。奇怪的是为什么主标签似乎预定有更多空间,但这是一个很好的解决方案,谢谢!

标签: r ggplot2 margin axis


【解决方案1】:

我有同样的问题,使用第二部分,

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

为我工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多