本文介绍了更改geom默认外观仅作为主题组件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于自定义ggplot2主题,我想更改某些geom的默认外观,例如,我要用红点代替黑点.

For a custom ggplot2 theme I'd like to change the default aesthetic of some geom, say I want red dots instead of black dots.

来自此答案我知道我们可以使用函数update_geom_default更改geom的默认值,但我想知道是否只有在调用theme_red_dots时才可以更改颜色?

From this answer I know we can change defaults for a geom using the function update_geom_default but I wonder if it is possible to change the colour only when we call theme_red_dots?

我天真尝试的例子:

library(ggplot2)

theme_red_dots <- function(...) {
  update_geom_defaults("point", list(colour = "red"))
  theme_minimal() +
    theme(...)
}

在这里看起来不错:

ggplot(mtcars, aes(mpg, disp)) +
  geom_point() +
  theme_red_dots()

但是我想在我打电话时再把点变黑

But I'd like the points to be black again when I call

ggplot(mtcars, aes(mpg, disp)) +
  geom_point()

提前谢谢!

下面是一个为什么我认为这可能有用的示例.我们可以很容易地将panel.background更改为黑色,但是如果我们不将美感映射到颜色,则将无法看到这些点. (当然可以讨论此theme_black的用处,但我想避免对此争论不休.)

Below is an example of why I thought this could be useful. We can change panel.background to be black fairly easy but this would make it impossible to see the points if we don't map an aesthetic to colour. (The usefulness of this theme_black can certainly be discussed, but I would like to avoid an argument about that.)

theme_black <- function(...) {
  theme_minimal() +
    theme(panel.background = element_rect(fill = "black")) +
    theme(...)
}

# update_geom_defaults("point", list(colour = "black"))
ggplot(mtcars, aes(mpg, disp)) +
  geom_point() +
  theme_black()

在这里可以更改geom_point()中点的颜色(请参阅@ zx8754答案),但这需要theme_black()的用户进行更改,而我想知道是否有一种方法可以正确执行此操作在theme_*内.

Changing the colour of the points inside geom_point() is an option here (see @zx8754 answer), but this requires the user of theme_black() to change it, while I am wondering if there is a way to do this right inside theme_*.

推荐答案

ggplot2 的发行版本目前没有提供实现此目的的方法.但是,这是一个相当老的功能请求,并且已经自2018年夏季以来一直在开发.

The released version of ggplot2 doesn't currently offer a way to do this. However, this is a fairly old feature request and has been under development since the summer of 2018.

这篇关于更改geom默认外观仅作为主题组件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 23:11