ggplot2 axis.text边距,比例尺位置已修改

时间:2018-11-05 18:09:09

标签: r ggplot2

我不确定是否遇到错误或执行不正确。在ggplot中指定axis.text边距并移动轴的位置时,设置将不会保留。

在不移动轴文本的情况下,轴周围有足够的空间:

library(ggplot)

ggplot(mtcars, aes(mpg, wt)) +
    geom_point() +
    theme(axis.text.y = element_text(color = "red", margin = margin(40, 40, 40, 40)))

plot with extra margins

但是,当头寸改变时,边距不适用:

ggplot(mtcars, aes(mpg, wt)) +
    geom_point() +
    scale_y_continuous(position = "right") + #This is the new line
    theme(axis.text.y = element_text(color = "red", margin = margin(40, 40, 40, 40))) 

enter image description here

我希望无论margin.text是在右边还是在左边,边距都可以保留。我在做错什么吗?

1 个答案:

答案 0 :(得分:2)

我认为这是因为右侧y轴标签的外观由axis.text.y.right中的theme()决定,虽然它是从axis.text.y继承的,但 axis.text.y.right本身未说明的参数

根据?theme中的详细信息,axis.text.y.right的继承链如下:

axis.text.y.right-> axis.text.y-> axis.text-> text

ggplot中的默认主题为theme_grey。在控制台中输入theme_grey(末尾没有()),您会看到完整的功能。让我们看一下相关的位:

function(base_size = 11, base_family = "", base_line_size = base_size/22, 
         base_rect_size = base_size/22) {

  half_line <- base_size/2

  theme(text = element_text(family = base_family, 
                            face = "plain", 
                            colour = "black",
                            size = base_size, 
                            lineheight = 0.9, 
                            hjust = 0.5, 
                            vjust = 0.5, 
                            angle = 0, 
                            margin = margin(), 
                            debug = FALSE), 

        axis.text = element_text(size = rel(0.8), 
                                 colour = "grey30"), 

        axis.text.y = element_text(margin = margin(r = 0.8 * half_line/2), 
                                   hjust = 1), 

        axis.text.y.right = element_text(margin = margin(l = 0.8 * half_line/2), 
                                         hjust = 0), 
        ...
        complete = TRUE)
}

?element_text显示element_text期望的参数的完整列表:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL, margin = NULL, debug = NULL, inherit.blank = FALSE)

鉴于所有继承,axis.text.y.righttheme_grey的实际参数是什么?

  • 家庭= base_family(来自text
  • face = "plain"(来自text
  • colour = "grey30"(来自axis.text,覆盖text的{​​{1}})
  • 大小= "black"的80%(来自base_size的{​​{1}}的{​​{1}}的{​​{1}}修改)
  • just = axis.text(来自rel(0.8),覆盖text的{​​{1}},覆盖base_size的{​​{1}})
  • vjust = 0(来自axis.text.y.right
  • angle = axis.text.y(来自1
  • lineheight = text(来自0.5
  • 保证金= 0.5(来自text,覆盖0的{​​{1}},覆盖text的{​​{1}})
  • debug = 0.9(来自text
  • inherit.blank = margin(l = 0.8 * half_line/2)axis.text.y.right的默认参数)

这样,给定一段类似下面的代码,axis.text.y将继承margin = margin(r = 0.8 * half_line/2(它将覆盖text的{​​{1}})。但是由于它具有自己的margin参数,因此不会继承margin()

FALSE

指定text而不是FALSE可以解决问题:

element_text