DJV
DJV

Reputation: 4873

ggplot2 - remove panel top border

I'm want to remove only the top part of my graph. I found some directions here and here. However, they remove all the borders or the top and left. I know that I should probably use the argument panel.border with element_blank() or element_rect() but I cannot find the correct way to define it.

I'm looking for this:

enter image description here

library(tidyverse)

mtcars %>% 
  ggplot(aes(factor(cyl), disp)) + 
  geom_boxplot() + 
  jtools::theme_apa() + 
  theme(
    panel.border = element_blank())

Will results with:

enter image description here

Upvotes: 8

Views: 5101

Answers (3)

Yuriy Barvinchenko
Yuriy Barvinchenko

Reputation: 1595

One more option (with some advice from Tjebo)

library(tidyverse)

mtcars %>% 
  ggplot(aes(factor(cyl), disp)) + 
  geom_boxplot() + 
  scale_y_continuous(sec.axis = sec_axis(~ .))+
  jtools::theme_apa() +
  theme(
    axis.line.x.bottom = element_line(color = 'black'),
    axis.line.y.left   = element_line(color = 'black'),
    axis.line.y.right  = element_line(color = 'black'),
    axis.text.y.right  = element_blank(),
    axis.ticks.y.right = element_blank(),
    panel.border       = element_blank())

Upvotes: 9

tjebo
tjebo

Reputation: 23807

Another option is a massive cheat... Use theme_classic and add a segment

library(tidyverse)

mtcars %>% 
  ggplot(aes(factor(cyl), disp)) + 
  geom_boxplot() + 
  #jtools::theme_apa() + 
  theme_classic() +
  annotate(geom = 'segment', x= Inf, xend = Inf, y = -Inf, yend = Inf)

Created on 2020-01-20 by the reprex package (v0.3.0)

Upvotes: 4

JaiPizGon
JaiPizGon

Reputation: 486

Using one of the references you have posted, you end up in this script (thanks to Rudolf Cardinal and Alex Holcombe). You can use the function theme_border() to plot the borders you want. To do so, just download the script provided in the link, put it in your working directory and execute the following code:

library(tidyverse)
library(grid)
source("rnc_ggplot2_border_themes_2013_01.r")
mtcars %>% 
  ggplot(aes(factor(cyl), disp)) + 
  geom_boxplot() + 
  jtools::theme_apa() + 
  theme(
    panel.border = theme_border(type = c("bottom","right","left")))

plotwithoutborders

Hope this helps!

Upvotes: 5

Related Questions