简体   繁体   中英

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. 在此处输入图片说明

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

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)]) )

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],'%'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM