Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

r - Can ggplot theme formatting be saved as an object?

TL;DR: How do I save the plotting axis text and sizes and et cetera an object to make my code shorter?

Say for example I wanted to plot different data with potentially different geoms but use the same axis text sizing and titles.

It would look like this in made up code

ggplot(data = df, aes(x = x, y = y) + geom_line() +
    ylab("my y axis") +
    xlab("my x axis") +
    opts(title = "my title") +
    theme(axis.text=element_text(size=20),
    axis.title=element_text(size=14,face="bold"))


ggplot(data = new_df, aes(x = whatever, y = something) + geom_anythingelse() +
    ylab("my y axis") +
    xlab("my x axis") +
    opts(title = "my title") +
    theme(axis.text=element_text(size=20),
    axis.title=element_text(size=14,face="bold"))

#...

How or can I save

my_theme <-   ylab("my y axis") +
              xlab("my x axis") +
              opts(title = "my title") +
              theme(axis.text=element_text(size=20),
              axis.title=element_text(size=14,face="bold"))

as its own object to add to ggplot when I like. Is ggplot flexible enough to accommodate my need here?

ggplot(data = df, aes(x = x, y = y) + geom_point() +
my_theme

Does this question violate the object naming philosophy that ggplot was built on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make a theme object without any problems, e.g:

mytheme<-theme(panel.background=element_rect(colour="green"))

It is even easier, if this is your standard theme to type

old_theme<- theme_update(panel.background=element_rect(colour="green"))

In the former case you write:

ggplot(...)+mytheme

while in the latter, because your custom theme is now the standard theme, it is only necessary to type:

ggplot(...)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...