zhiwei li
zhiwei li

Reputation: 1711

show a specific value at x axis without break in ggplot2

Context

I want to show a specific value at x axis in ggplot2. It is 2.84 in the Reproducible code.

I found the answer at How can I add specific value to x-axis in ggplot2?

It very close to my need.

Question

Is there some way that do not need set breaks and labels in scale_x_continuous to show a specific value at x axis.

Because I need to draw a large number of similar images, setting the breaks and labels for each image will be very tedious.

Reproducibale code

# make up some data
d <- data.frame(x = 6*runif(10) + 1,
                y = runif(10))

# generate break positions
breaks = c(seq(1, 7, by=0.5), 2.84)
# and labels
labels = as.character(breaks)

# plot
ggplot(d, aes(x, y)) + geom_point() + theme_minimal() +
  scale_x_continuous(limits = c(1, 7), breaks = breaks, labels = labels,
                     name = "Number of treatments")

enter image description here

Upvotes: 0

Views: 107

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173928

You can automate this process by creating a wrapper round scale_x_continuous that inserts your break into a vector of pretty breaks:

scale_x_fancy <- function(xval, ...) {
  scale_x_continuous(breaks = ~ sort(c(pretty(.x, 10), xval)), ...)
}

So now you just add the x value(s) where you want the extra break to appear:

ggplot(d, aes(x, y)) + 
  geom_point() + 
  theme_minimal() +
  scale_x_fancy(xval = 2.84, name = "Number of treatments")

enter image description here

Upvotes: 2

Related Questions