Vandenman
Vandenman

Reputation: 3176

ggplot with bty="n", or how to add grid coordinates to plot coordinates

I have a question that expands on this one. Basically I want to add bty = "n" to a ggplot2 graph in a proper way. Emphasis on proper here because the solution in the other question almost what I want, except for this detail: enter image description here I would like it if the axis line would continue until the end of the tick, not until the middle of it. First, code for the graph:

library(ggplot2)
library(grid)

graph = ggplot(faithful, aes(x=eruptions, y=waiting)) +
   geom_point(shape=21) +
    theme(
    # tick width, a bit exaggerated as example
    axis.ticks = element_line(size = 5, color = "gray") 
    )
graph # graph with no axis lines

# get axis limits
gb = ggplot_build(graph)
xLim = range(gb$layout$panel_ranges[[1]]$x.major_source)
yLim = range(gb$layout$panel_ranges[[1]]$y.major_source)

# add lines
graph +
    geom_segment(y = -Inf, yend = -Inf, x = xLim[1], xend = xLim[2]) +
    geom_segment(x = -Inf, xend = -Inf, y = yLim[1], yend = yLim[2])

So the problem is: I draw on the x-axis from 50 till 90. But, the tickmarks are centered on 50 and 90, therefore they extend by half of size = 5 on each side. ?element_line tells me that line/ border size is by default in mm. Thus I want to draw the line from 50 - 5mm / 2 until 90 + 5mm / 2. I tried (many variations of) the following:

xLim = range(gb$layout$panel_ranges[[1]]$x.major_source)
yLim = range(gb$layout$panel_ranges[[1]]$y.major_source)

uType = "npc"
uType2 = "mm" 

# attempt conversion of units
xLim[1] = xLim[1] - convertWidth(unit(2.5, units = uType2),
                      unitTo = uType, valueOnly = TRUE)
xLim[2] = xLim[2] +  convertWidth(unit(2.5, units = uType2),
                      unitTo = uType, valueOnly = TRUE)

yLim[1] = yLim[1] - convertHeight(unit(2.5, units = uType2),
                             unitTo = uType, valueOnly = TRUE)
yLim[2] = yLim[2] - convertHeight(unit(2.5, units = uType2),
                             unitTo = uType, valueOnly = TRUE)

# redraw graph    
cairo_pdf("Rplot.pdf")
graph +
    geom_segment(y = -Inf, yend = -Inf, x = xLim[1], xend = xLim[2]) +
    geom_segment(x = -Inf, xend = -Inf, y = yLim[1], yend = yLim[2])
dev.off()

But no luck whatsoever. Any ideas?

Upvotes: 0

Views: 428

Answers (2)

January
January

Reputation: 17120

Much simpler nowadays: use the geom_rangeframe() from the package ggthemes(). I think it does exactly what you want.

Upvotes: 1

baptiste
baptiste

Reputation: 77116

I believe you'd have to write a drawDetails method or similar to do the unit calculation at drawing time for this to work.

Alternatively (and perhaps easier), you could write a custom tick grob that extends to cover the axis line.

enter image description here

(Note that the two axes have different line widths because of their z-order IIRC; I thought that bug had been fixed).

library(ggplot2)
library(grid)


element_grob.element_custom_x <- function (element, x = 0:1, y = 0:1, colour = NULL, size = NULL, 
                                           linetype = NULL, lineend = "butt", default.units = "npc", id.lengths = NULL, 
                                           ...) 
{
  gp <- gpar(lwd = ggplot2:::len0_null(size * .pt), col = colour, lty = linetype, 
             lineend = lineend)
  element_gp <- gpar(lwd = ggplot2:::len0_null(element$size * .pt), col = element$colour, 
                     lty = element$linetype, lineend = element$lineend)
  arrow <- if (is.logical(element$arrow) && !element$arrow) {
    NULL
  }
  else {
    element$arrow
  }
  g1 <- polylineGrob(x, y, default.units = default.units, 
                     gp = utils::modifyList(element_gp, gp), 
                     id.lengths = id.lengths, arrow = arrow, ...)

  vertical <- length(unique(element$x)) == 1 && length(unique(element$y)) >= 1

  g2 <- grid::editGrob(g1, y=y + unit(1,"mm"), gp=utils::modifyList(gp, list(col="green")), name="new")

  grid::grobTree(g2, g1)

}


element_grob.element_custom_y <- function (element, x = 0:1, y = 0:1, colour = NULL, size = NULL, 
                                           linetype = NULL, lineend = "butt", default.units = "npc", id.lengths = NULL, 
                                           ...) 
{
  gp <- gpar(lwd = ggplot2:::len0_null(size * .pt), col = colour, lty = linetype, 
             lineend = lineend)
  element_gp <- gpar(lwd = ggplot2:::len0_null(element$size * .pt), col = element$colour, 
                     lty = element$linetype, lineend = element$lineend)
  arrow <- if (is.logical(element$arrow) && !element$arrow) {
    NULL
  }
  else {
    element$arrow
  }
  g1 <- polylineGrob(x, y, default.units = default.units, 
                     gp = utils::modifyList(element_gp, gp), 
                     id.lengths = id.lengths, arrow = arrow, ...)

  g2 <- grid::editGrob(g1, x=x + unit(1,"mm"), gp=utils::modifyList(gp, list(col="green")), name="new")

  grid::grobTree(g2, g1)

}


## silly wrapper to fool ggplot2
x_custom <- function(...){
  structure(
    list(...), # this ... information is not used, btw
    class = c("element_custom_x","element_blank", "element") # inheritance test workaround
  ) 

}
y_custom <- function(...){
  structure(
    list(...), # this ... information is not used, btw
    class = c("element_custom_y","element_blank", "element") # inheritance test workaround
  ) 

}

graph = ggplot(faithful, aes(x=eruptions, y=waiting)) +
  geom_point(shape=21) + theme_minimal() +
  theme(
    axis.ticks.x = x_custom(size = 5, colour = "red") ,
    axis.ticks.y = y_custom(size = 5, colour = "red") ,
    axis.ticks.length = unit(2,"mm")
  )
graph # graph with no axis lines
gb <- ggplot_build(graph)
xLim = range(gb$layout$panel_ranges[[1]]$x.major_source)
yLim = range(gb$layout$panel_ranges[[1]]$y.major_source)


graph +
  geom_segment(y = -Inf, yend = -Inf, x = xLim[1], xend = xLim[2],lwd=2) +
  geom_segment(x = -Inf, xend = -Inf, y = yLim[1], yend = yLim[2],lwd=2)

Upvotes: 1

Related Questions