Skip to content

Instantly share code, notes, and snippets.

@smach
Created July 28, 2021 15:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smach/234ca2684d71c8c3c7c985ebec0d4ddf to your computer and use it in GitHub Desktop.
Save smach/234ca2684d71c8c3c7c985ebec0d4ddf to your computer and use it in GitHub Desktop.
Only display every n data point in ggplot2
# Function to set all vector items to blank except for every nth item
everyn <- function(myvec, n){
myvec <- sort(unique(myvec))
for(i in 1:length(myvec)) {
if( i %% n != 1) {
myvec[i] <- ""
}
}
return(myvec)
}
# Then add this line to your ggplot graph, where mydf is the data frame with data being graphed, xcol is the unquoted name of the x-axis column, and n is every nth item you want to display:
scale_x_discrete(labels = everyn(mydf$xcol, n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment