在ggplot2中仅绘制x轴和y轴边框(无框)?

8
一些期刊的惯例是在绘图中只显示 x 和 y 轴,而不是整个绘图区域周围的框。我该如何在 ggplot2 中实现这一点?我尝试了来自此处theme_minimal_cb_L,但它似乎擦除了绘图周围的整个框(没有留下 x 和 y 轴),如下所示:

enter image description here

这是我正在使用的代码:
dat <- structure(list(x = c(0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1, 1.05, 
    1.1, 1.15, 1.2, 1.25, 1.3), y1 = c(34, 30, 26, 23, 21, 19, 17, 
    16, 15, 13, 12, 12, 11), y2 = c(45, 39, 34, 31, 28, 25, 23, 21, 
    19, 17, 16, 15, 14)), .Names = c("x", "y1", "y2"), row.names = c(NA, 
    -13L), class = "data.frame")


library(reshape2); library(ggplot2)
dat2 <- melt(dat, id='x')

theme_minimal_cb_L <- function (base_size = 12, base_family = "", ...){
  modifyList (theme_minimal (base_size = base_size, base_family = base_family),
              list (axis.line = element_line (colour = "black")))
}

ggplot(data=dat2, aes(x=x, y=value, color=variable)) + 
    geom_point(size=3) + geom_line(size=.5) +
    theme_minimal_cb_L()

请注意,我使用的是ggplot2版本“0.9.2.99”来创建此内容。如果您使用的版本较低,则可以通过与我上面显示theme_minimal_cb_L相同的链接获得theme_minimal - Tyler Rinker
2个回答

11
axis.line.x()axis.line.y()似乎比axis.line()更有效。请将以下代码添加到您的图表中:
... + theme(panel.border = element_blank(),
axis.line.x = element_line(size = 0.5, linetype = "solid", colour = "black"),
axis.line.y = element_line(size = 0.5, linetype = "solid", colour = "black")) + ...

会起到效果。


9
我理解您的意思是只想保留图表左侧和底部的线条 - 是这样吗?
theme(panel.border = element_blank(), axis.line = element_line())

使用panel.border可以移除整体边框,然后使用axis.line添加x轴和y轴线。


编辑:由于您发布的额外主题内容对我无效。我将发布我实际运行的代码

dat <- structure(list(x = c(0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1, 1.05, 
    1.1, 1.15, 1.2, 1.25, 1.3), y1 = c(34, 30, 26, 23, 21, 19, 17, 
    16, 15, 13, 12, 12, 11), y2 = c(45, 39, 34, 31, 28, 25, 23, 21, 
    19, 17, 16, 15, 14)), .Names = c("x", "y1", "y2"), row.names = c(NA, 
    -13L), class = "data.frame")


library(reshape2); library(ggplot2)
dat2 <- melt(dat, id='x')

ggplot(data=dat2, aes(x=x, y=value, color=variable)) + 
    geom_point(size=3) + geom_line(size=.5) +
    theme(panel.border = element_blank(), axis.line = element_line())

# or using the template you used from talkstats...
ggplot(data=dat2, aes(x=x, y=value, color=variable)) + 
    geom_point(size=3) + geom_line(size=1.5) +
    scale_y_continuous(breaks=seq(0, 45, by=5)) +
    scale_x_continuous(breaks=seq(.7, 1.3, by=.05)) +
    theme_bw() + ylab("Sample Size") + xlab("Mean Difference") +
    theme(legend.position="bottom", legend.title=element_blank(),
        legend.key = element_rect(colour = 'white'), 
        legend.background = element_rect(colour = "black")) +
    ggtitle("Sample Size vs. Mean Difference by Power") +
    theme(panel.border = element_blank(), axis.line = element_line())

我在这里运行您发布的代码时实际上遇到了一个错误,所以我将其添加到您在TS上发布的代码中。 - Dason
PS:这不是一个跨贴,只是从我在Talkstats上为一个帖子提供帮助中产生的好奇心。我在这里发布了较少的代码以保持最小化。Dason发布的代码是我对该帖子的回答(链接) - Tyler Rinker
那太完美了。这肯定会在我未来创作的视觉中派上用场。谢谢你。 - Tyler Rinker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接