ekstroem
ekstroem

Reputation: 6151

Truncated axis lines in ggplot2

I would like to use ggplot() to produce a graph with truncated axis lines similar to what is seen in the lower left corner in the plot below (created with base R graphics).

enter image description here

I guess that I need to set the axis.line argument in my ggplot theme to something other than element_line(), but I have no idea to what. Here's the code I currently have

library("ggplot2")
library("ggrepel")

tab <- data.frame(
    Average=rnorm(40, mean=12, sd=3),
    SD =rnorm(40, mean=12, sd=3),
    names = LETTERS[1:40],
    class_num = sample(1:4, size=40, replace=TRUE)
    )

ggplot(data=tab,
       aes(x=Average, y=SD, label=rownames(tab))) + 
    stat_smooth(method="lm", size=1, se=FALSE, col="black") +
    geom_point(aes(col=factor(class_num), shape=factor(class_num)), size=2) + 
    geom_text_repel(size=3) + 
    xlab(expression("Seasonal average" ~ widehat(ETI)[m])) +
    ylab(expression("Seasonal SD of" ~ widehat(ETI)[m])) + 
    scale_x_continuous(breaks =seq(9.2, 11.8, length.out=5)) + 
    scale_shape_manual(values=c(15, 16, 17, 18)) +
    scale_color_manual(values=c("#CC0000", "darkgreen", "#0000CC", "#000000")) + 
    theme_classic() + 
    theme(legend.position="none",
          axis.ticks.length = unit(.25, "cm"), 
          axis.line = element_line())

This produces the following plot where the x-axis and y axis lines are connected in the lower left-hand corner.

enter image description here

Upvotes: 0

Views: 1598

Answers (1)

DaveArmstrong
DaveArmstrong

Reputation: 21757

How about this, it makes use of the coord_capped_cart() function from the lemon package. There's a nice discussion here.

library("ggplot2")
library("ggrepel")
library(lemon)
tab <- data.frame(
  Average=rnorm(40, mean=12, sd=3),
  SD =rnorm(40, mean=12, sd=3),
  names = LETTERS[1:40],
  class_num = sample(1:4, size=40, replace=TRUE)
)

ggplot(data=tab,
       aes(x=Average, y=SD, label=rownames(tab))) + 
  stat_smooth(method="lm", size=1, se=FALSE, col="black") +
  geom_point(aes(col=factor(class_num), shape=factor(class_num)), size=2) + 
  geom_text_repel(size=3) + 
  xlab(expression("Seasonal average" ~ widehat(ETI)[m])) +
  ylab(expression("Seasonal SD of" ~ widehat(ETI)[m])) + 
  scale_x_continuous(breaks =seq(7, 17, length.out=5)) + 
  scale_y_continuous(breaks=seq(5,18, length.out=5)) +
  scale_shape_manual(values=c(15, 16, 17, 18)) +
  scale_color_manual(values=c("#CC0000", "darkgreen", "#0000CC", "#000000")) + 
  theme_classic() + 
  theme(legend.position="none",
        axis.ticks.length = unit(.25, "cm"), 
        axis.line = element_line()) + 
  coord_capped_cart(bottom=capped_horizontal(), 
                    left=capped_vertical(capped="both"))

enter image description here

Upvotes: 3

Related Questions