Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 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 Answer

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(...)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...