Username
Username

Reputation: 3663

How do I add a custom `labels` for just one tick?

I'm making a chart where the X axis will have '%'.

ggplot(
  data = cars,
  aes(
    x = speed,
    y = dist
  )
) + 
  geom_point() +
  scale_x_continuous(
    labels = function(x) paste0(x,'%'),
  )

This produces a chart. enter image description here

I only want either the first tick or last tick on the X axis to have the '%'. How do I do this?

Upvotes: 0

Views: 97

Answers (2)

Sri Lakshmi
Sri Lakshmi

Reputation: 11

Format the function in labels to get '%' for the first tick label only

labels = function(x) c(paste0(x[1],'%'),x[-(1)]

To get '%' for last tick label only

labels = function(x) c(x[1:length(x)-1] , paste0(rev(x)[1],'%'))

Upvotes: 1

konvas
konvas

Reputation: 14346

Just change your function to

labels = function(x) c(paste0(x[1] * 100, '%'), x[-1])

(note you may have to adjust your breaks and/or limits because in the updated example you posted, the first element of x is not plotted, so in that case you would need to do c(paste0(x[1:2] * 100, '%'), x[-(1:2)]))

Upvotes: 3

Related Questions