4
votes

I have some data with x-values on a 0-to-100 scale, like this:

library(ggplot2)
set.seed(42)
df <- data.frame(x=c(rep(100, 20), runif(100, min=0, max=100)),
                 y=rnorm(120, mean=4, sd=2))

A simple scatterplot, produced by this code:

ggplot(df, aes(x=x, y=y)) +
    geom_point(size=5) +
    theme(panel.grid.major=element_line(color='black'),
          panel.grid.minor=element_line(color='black'),
          panel.background=element_rect(fill='white'))

looks like this: Ordinary scatterplot with a healthy x-margin.

But to emphasize that x-values outside the 0-to-100 range are meaningless, I want to clip the x-axis and the horizontal gridlines exactly at x=0 and x=100. I'm given to understand that the proper way to do this is with expand, by adding scale_x_continuous(limits=c(0, 100), expand=c(0, 0)) to my ggplot object. The result:Scatterplot with no margins and with clipped markers and x-labels

This shortens the gridlines, but it also clips the scatterplot markers at the left and right margins, as well as the 100 label on the x-axis. Can I cut off just the x-axis and grid lines before the margin, but render the markers and axis labels as if the margin were still there?

1
Maybe not what you're looking for, but geom_rangeframe from ggthemes package will achieve this. Look at theme_tufte example and how to specify the limits of geom_rangeframe. - mikeck

1 Answers

3
votes

You can control the range of the grid lines by using geom_segment to create grid lines. For example:

library(ggplot2)
library(scales)

yr = pretty(df$y)
xr = pretty(df$x)

ggplot() +
  geom_segment(aes(y=rep(min(yr), length(xr)), yend=rep(max(yr), length(xr)),
                   x=xr, xend=xr), colour="grey70") +
  geom_segment(aes(x=rep(min(xr), length(yr)), xend=rep(max(xr), length(yr)),
                   y=yr, yend=yr), colour="grey70") +
  geom_point(data=df, aes(x,y), size=5) + 
  scale_y_continuous(breaks=yr, expand=c(0,0.02*diff(range(df$y)))) +
  scale_x_continuous(breaks=xr, expand=c(0,0.02*diff(range(df$x)))) +
  theme_classic() +
  theme(axis.line=element_blank()) +
  labs(x="x", y="y")

enter image description here