Niek de Klein
Niek de Klein

Reputation: 8824

How can I change the x-axis ticks while still limiting the x-axis range?

I have the following example dataframe that I want to plot from -4, -1:

test_x <- c(-3.5, -2, -1, -0.5)
test_y <- c(1,2,3,4)
df <- data.frame(x=test_x, y=test_y)
library(ggplot2)
ggplot(df, aes(x=x, y=y)) + 
  geom_point() +
  xlim(-4, -1)

enter image description here

I want to show the -4 tick and I want to exclude the -0.5 point. However, I also want to change the x-axis tick label. For continuous data I found scale_x_continuous

ggplot(df, aes(x=x, y=y)) + 
  geom_point() +
  scale_x_continuous(breaks=c(-4, -3, -2, -1), labels=c("a","b","c","d"))

enter image description here

However, this does not show the a tick, and it does not exclude the point at -0.5. Trying to limit it again with x_lim gives the error Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

How can I change the x-axis ticks while still limiting the x-axis range?

Upvotes: 3

Views: 1236

Answers (1)

zx8754
zx8754

Reputation: 56004

Use limits inside scale:

ggplot(df, aes(x = x, y = y)) + 
  geom_point() +
  scale_x_continuous(breaks = c(-4, -3, -2, -1),
                     labels = c("a", "b", "c", "d"),
                     limits = c(-4, -1))

Note, by applying limits c(-4, -1) we are dropping one point, so we will get a warning:

Warning message: Removed 1 rows containing missing values (geom_point).


As an alternative to limits, you can also use coord_cartesian(xlim = c(-4, -1)) which does not change the underlying data like setting limits does (and consequently, you will also not get a warning about removed rows):

ggplot(df, aes(x=x, y=y)) + 
  geom_point() +
  scale_x_continuous(breaks = c(-4, -3, -2, -1),
                     labels = c("a", "b", "c", "d")) +
  coord_cartesian(xlim = c(-4, -1))

Upvotes: 7

Related Questions