【问题标题】:ggplot2 theme_classic display x and y axes [duplicate]ggplot2 theme_classic 显示 x 和 y 轴 [重复]
【发布时间】:2016-03-12 16:28:33
【问题描述】:

我无法用 ggplot2 重现一个简单的图表。我的目标是显示 x 和 y 轴。这个取自网站的基本示例不起作用,我不明白为什么。任何见解都非常感谢!

library(ggplot2)
df <- data.frame(x = 1:3, y = 1:3)
ggplot(df, aes(x, y)) + geom_point()+  theme_classic() + ggtitle("theme_classic()")

我也尝试过使用

theme(axis.line = element_line(colour = "grey50"))

但我有同样的问题,即我得到这个

而不是预期的(不同数据集的示例,在我的示例中,点是缺少 x 和 y 轴)

【问题讨论】:

  • 你是从cowplot那里得到的吗? theme_classic 为您提供文档所拥有的内容 docs.ggplot2.org/current/ggtheme.html ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() + cowplot::theme_cowplot()
  • 这在 ggplot 2.0.0 中有效,但在 ggplot 2.1.0 中不再有效。不过,您仍然可以通过添加 + theme(axis.line.x = element_line(color = "black"), axis.line.y = element_line(color = "black")) 来治愈它。也许他们改变了theme-defaults.r
  • 一个错误:见here 和这个bug report

标签: r ggplot2


【解决方案1】:

Mayby 你在找theme_bw()

ggplot(df, aes(x, y)) + geom_point() + theme_bw()

这是theme_classic()的解决方案

ggplot(df, aes(x, y)) + 
  geom_point() + 
  theme_classic() + 
  theme(
    axis.line.x = element_line(colour = "grey50"),
    axis.line.y = element_line(colour = "grey50")
  )

当需要查看主题的结构时,可以使用 dput 输出其值:

 dput(theme_classic())

这可以让您查看结果列表的哪些名称具有执行“消隐”的代码:

 theme_classic()[grepl("axis.line", names(theme_classic()) )]

$axis.line
List of 4
 $ colour  : chr "black"
 $ size    : NULL
 $ linetype: NULL
 $ lineend : NULL
 - attr(*, "class")= chr [1:2] "element_line" "element"

$axis.line.x
 list()
 - attr(*, "class")= chr [1:2] "element_blank" "element"

$axis.line.y
 list()
 - attr(*, "class")= chr [1:2] "element_blank" "element"

【讨论】:

  • 这就是 Mac 所需要的,与其他一些报告不同,它没有绘制任何轴线。
  • 请注意,它可能取决于 ggplot2 的版本。 theme() 在 2.0.0 中发生了很大变化,甚至更高版本在 theme() 中引入了一些小的变化
  • 我的盒子是packageDescription('ggplot2')$Version [1] "2.1.0"
【解决方案2】:

奇怪的是,让您的第一个示例完全按照您希望的方式运行没有问题,我无法解释。但也许你可以试试我通常做的:

ggplot(df, aes(x, y)) + 
  geom_point() + 
  theme(axis.line = element_line(colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank()) 

【讨论】:

  • 你是什么packageVersion("ggplot2")?它在 2.0.0 中有效,但在 2.1.0 中不再有效。
  • 是的,我有包版本 2.1.0。谢谢@lukeA。我该怎么办?
  • @Matilde 添加+ theme(axis.line.x = element_line(color = "black"), axis.line.y = element_line(color = "black"))。模板中默认的axis.line = element_line(color = "black") 不起作用。
  • @lukeA ,我有点困惑,如果我必须在图表周围做方框,panel.border=element.rect(colour="black") 也不起作用......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 2010-11-19
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多