Cut off the lines of the diffusion grid, but not the markers exactly within the axis

I have data with x-values ​​on a scale from 0 to 100, for example:

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 scatter chart created 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 that: Normal scatter plot with healthy x-margin.

But in order to emphasize that values ​​of x outside the range from 0 to 100 do not make sense, I want to copy the x axis and horizontal grid lines exactly at x = 0 and x = 100. I was given to understand that the correct way to do this is with expandby adding scale_x_continuous(limits=c(0, 100), expand=c(0, 0))to my object ggplot. Result:Scatterplot borderless and with clipped markers and x-tags

This shortens the grid lines, but also copies the scatter plot markers on the left and right edges, as well as on the label 100 along the x axis. Can I cut only along the x axis and the grid line in front of the edge, but make the markers and marks of the axes as if the margin is still there?

+4
1

, geom_segment . :

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

+3

Source: https://habr.com/ru/post/1685338/


All Articles