简体   繁体   中英

How to keep top and bottom axes in ggplot, while removing the panel border

I would like to keep both x axes (bottom and top), while removing the panel border (or both y axes, left and right).

Code:

library(ggplot2)
p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue") +
  theme_bw() +
  theme(axis.title.y=element_blank(),
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        panel.border = element_blank(),
        axis.line.x = element_line(size = 0.5, linetype = "solid", colour = "lightgrey"),
        axis.line.y = element_blank(),
        panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.background = element_blank())
print(p1)

在此处输入图像描述

This can be accomplished with sec_axis .

In order to reproduce your white background, I'll add theme_bw() before the call to theme ; this also helps me break out the lower x-axis line, then I'll add the second axis.

library(ggplot2)
p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue") +
  theme_bw() +
  theme(axis.title.y=element_blank(),
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        panel.border = element_blank(),
        axis.line.x = element_line(size = 2, linetype = "solid", colour = "lightgrey"),
        axis.line.y = element_blank(),
        panel.grid.minor = element_blank(),
        panel.grid.major.x = element_blank())

# original
p1
# both lines
p1 + scale_x_continuous(sec.axis=sec_axis(~.))

并排的 ggplots,第二个带有顶/底线

(side-by-side here for space/presentation, the code did not do that)


Side note: @chemdork123's suggested answer does work here: use annotate to add a specific geometry. While I don't prefer this method, it can suffice. ( 'green' retained from the linked answer.)

p1 + annotate(geom = 'segment', y = Inf, yend = Inf, color = 'green', x = -Inf, xend = Inf, size = 4)

向ggplot添加第二条轴线的替代方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM