【问题标题】:How to include axis breaks in a theme in ggplot2如何在ggplot2的主题中包含轴中断
【发布时间】:2014-08-12 09:54:54
【问题描述】:

在 ggplot2 中,我想为主题添加一些轴偏好,通常是中断和标题,以便在生成类似图形时减少重复代码。我尝试了以下方法,但由于 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()

【问题讨论】:

  • 你能提供一些数据和你的完整代码吗?对于您的问题,您会得到一个更好的、经过调整的答案。
  • 为什么 mpg 嵌入数据集不适合作为示例?这是我尝试将 x 轴标题/中断设置为当前主题的完整代码
  • 试试set_default_scale
  • @baptiste 这个功能在 0.9.3.1 中还存在吗?我只能找到0.8.9 的文档,使用时出现错误(Error: could not find function)。
  • @Lynda 正确,抱歉,我忘记了。请参阅this discussion 了解替代方案

标签: r ggplot2 axis-labels


【解决方案1】:

您不能对主题进行此操作。但是您可以保存您的坐标轴首选项,然后将它们添加到您的绘图中。或者在函数中定义你最喜欢的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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    相关资源
    最近更新 更多