[英]ggplot2 create custom theme with predefined labels
I have a very simple questions but didnt find an answer online.. I am not even sure if this functionality exists in ggplot2.我有一个非常简单的问题,但没有在网上找到答案。我什至不确定 ggplot2 中是否存在此功能。
For different types of plots, I usually create themes, so I dont have to type everything out each time I am regenerating a plot with different data.对于不同类型的情节,我通常会创建主题,因此每次使用不同数据重新生成 plot 时,我不必输入所有内容。
The code might look something like this:代码可能看起来像这样:
theme_UMAP <- function(x){
theme(...,
legend.key = element_rect(colour = NA),
legend.position = "bottom",
legend.direction = "horizontal",
legend.key.size= unit(0.8, "cm"),
legend.spacing = unit(0, "cm"),
legend.title = element_text(face="bold",size=15),
legend.text = element_text(size=14),
plot.margin=unit(c(2,1,1,1),"mm"),
strip.background=element_rect(colour="#f0f0f0",fill="#f0f0f0"),
strip.text = element_text(face="bold")}
Now for this particular theme, I know that the X-label will always be UMAP 1 and the Y-label will always be UMAP 2 .现在对于这个特定的主题,我知道 X 标签将始终是UMAP 1而 Y 标签将始终是UMAP 2 。 I would love to include this in the function by doing something like this:
我很乐意通过执行以下操作将其包含在 function 中:
theme_UMAP <- function(x){
theme(...,
legend.spacing = unit(0, "cm"),
legend.title = element_text(face="bold",size=15),
legend.text = element_text(size=14),
plot.margin=unit(c(2,1,1,1),"mm"),
strip.background=element_rect(colour="#f0f0f0",fill="#f0f0f0"),
strip.text = element_text(face="bold")+
xlab("UMAP 1")+
ylab("UMAP 2")}
However, this results in the following error:但是,这会导致以下错误:
Error:
! Theme element `x` is not defined in the element hierarchy.
Any ideas how to achieve what I am trying to do is very much appreciated!非常感谢任何关于如何实现我想要做的事情的想法!
Cheers!干杯!
First issue with your code is that you have put x/ylab
inside theme
.您的代码的第一个问题是您已将
x/ylab
放入theme
中。 Second, if you want to put multiple layers in function then use a list
:其次,如果你想在 function 中放置多层,那么使用一个
list
:
Using a minimal example based on mtcars
:使用基于
mtcars
的最小示例:
library(ggplot2)
theme_UMAP <- function(x) {
list(
theme(
legend.spacing = unit(0, "cm"),
legend.title = element_text(face = "bold", size = 15),
legend.text = element_text(size = 14),
plot.margin = unit(c(2, 1, 1, 1), "mm"),
strip.background = element_rect(colour = "#f0f0f0", fill = "#f0f0f0"),
strip.text = element_text(face = "bold")
),
xlab("UMAP 1"),
ylab("UMAP 2")
)
}
ggplot(mtcars, aes(hp, mpg)) +
geom_point() +
theme_UMAP()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.