如何在 ggplot2 主题 (ggtheme) 中设置默认线条大小?

Adh*_* R. 0 r ggplot2

我分叉了ggthemes git repo来制作我自己的自定义主题。我已经想出了如何做几乎所有我需要的事情,但有一个挂断电话。

我特别想设置默认sizegeom_line()我的ggtheme。

我现在在哪里,我必须做这样的事情:

economics %>%
    ggplot(aes(date, uempmed)) +
    geom_line(size = 1.75) +
    theme_mycustomtheme()
Run Code Online (Sandbox Code Playgroud)

当我更愿意只需要这样做时:

economics %>%
    ggplot(aes(date, uempmed)) +
    geom_line() +
    theme_mycustomtheme() # this would set the line size automatically
Run Code Online (Sandbox Code Playgroud)

我已经编辑了 mycustomtheme.R 文件,如下所示:

theme(
    # Elements in this first block aren't used directly, but are inherited
    # by others
    line =               element_line(
      color = "black", size = 1.75,
      linetype = 1, lineend = "butt"
    )
Run Code Online (Sandbox Code Playgroud)

请注意大小现在如何设置为 1.75。但是当我在实践中调用主题时,它似乎没有什么不同。

我将不胜感激任何关于我可能做错了什么的指示。谢谢!

Jan*_*yer 8

主题不影响几何体中的线条,只影响轴、网格线等中的线条。但是,您可以使用update_geom_defaults().

#specify geom to update, and list attibutes you want to change appearance of
update_geom_defaults("line", list(size = 1.75))

#now your graph will plot with the line size you defined as default
economics %>%
  ggplot(aes(date, uempmed)) +
  geom_line() 
Run Code Online (Sandbox Code Playgroud)

如果您添加update_geom_defaults("line", list(size = 1.75))到存储自定义主题的文件中,您的 geom 默认值也会在source()您创建 mycustomtheme.r 文件时更新,您将获得所需的线型。请注意,以这种方式设置默认值只会更改指定的确切几何图形 ( line),并且不会影响其他几何图形中的线元素(箱线图边框、误差线等),因此您需要为您计划的每个单独几何图形定义几何图形默认值用。