ggplot x-axis, y-axis ticks, labels, breaks and limits

Hi, I would like to have all ticks labelled on x-axis:

x<-rnorm(25)
y<-rnorm(25)
df<-data.frame(x,y)

library(ggplot2)

ggplot(df,aes(x,y))+geom_point()

in order not to have empty ticks (but all with labels) like this:

Additionally I would like to put some limits, for example on x-axis from -2 to 4.

How do I do this, please give me some hints where to start. Thank you.
Should I add scale_x_discreete or scale_x_continuous ?

You can set axis breaks to custom values with the breaks argument in scale_x_continuous and scale_y_continuous. Use the limits argument set axis ranges. If you don't want minor breaks (the gridlines with no axis labels that are marked in your example), then set minor_breaks=NULL:

library(ggplot2)

set.seed(2)
x<-rnorm(25)
y<-rnorm(25)
df<-data.frame(x,y)

ggplot(df,aes(x,y)) + 
  geom_point() +
  scale_x_continuous(breaks=seq(-3,2,0.5))

ggplot(df,aes(x,y)) + 
  geom_point() +
  scale_x_continuous(breaks=seq(-3,2,0.5), limits=c(-1,1))
#> Warning: Removed 11 rows containing missing values (geom_point).

ggplot(df,aes(x,y)) + 
  geom_point() +
  scale_x_continuous(breaks=seq(-3,2,0.5),
                     minor_breaks=NULL)

Created on 2021-10-27 by the reprex package (v2.0.1)

Thank you very much indeed Joels, this is absolutely fabulous and of great help.
I would like to kindly ask you if I want to have got labels even "to the full", to the last ticks, is it a way
to force it ?

If the graph limits don't already include the value of the "last tick", use the limits argument to ensure that the value is included. If the default breaks don't include a tick-mark at the desired value, then use the breaks argument to add a tick-mark at that value.

library(ggplot2)

d = data.frame(x=c(1.1, 1.9), y=c(1,2))

ggplot(d, aes(x,y)) + 
  geom_point()

ggplot(d, aes(x,y)) + 
  geom_point() +
  scale_x_continuous(limits=c(1,2))

Created on 2021-10-27 by the reprex package (v2.0.1)

Thank you Joels , I am very grateful.
best

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.