在ggplot2中,我想为主题添加一些轴首选项,通常是break和title,以便在生成类似的图形时重复性较少的代码。我尝试了以下内容,但由于scale_x_continuous
没有返回主题对象,因此无效。有没有办法让它发挥作用?
theme_set(theme_get() +
scale_x_continuous('this is x',breaks=seq(0,10,by=2)))
ggplot(mpg,aes(x=displ,y=year))+geom_point()
答案 0 :(得分:0)
你不能用主题做这件事。但您可以保存您的轴首选项,然后将它们添加到您的图中。或者在函数中定义您最喜欢的ggplot
版本:
require(ggplot2)
# define my favorite axes
x.axis <- scale_x_continuous('this is x', breaks=seq(0,10,by=2))
y.axis <- scale_y_continuous('this is y', breaks=seq(1990,2010,by=3))
xy.ggplot <- function(...) ggplot(...) + x.axis + y.axis
# use axes in plots
ggplot(mpg,aes(x=displ,y=year)) + geom_point()
ggplot(mpg,aes(x=displ,y=year)) + geom_point() + x.axis
xy.ggplot(mpg,aes(x=displ,y=year)) + geom_point()
# you can also overwrite ggplot
ggplot <- function(...) ggplot2:::ggplot(...) + scale_x_continuous('this is x', breaks=seq(0,10,by=2))
# use your version
ggplot(mpg,aes(x=displ,y=year)) + geom_point()
# to get standard ggplot
ggplot2::ggplot(mpg,aes(x=displ,y=year)) + geom_point()