Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the Y-axis tick label to custom expression in GGPLOT

Let say I have below ggplot

library(zoo)
library(quantmod)
library(ggplot2)
Data = data.frame('class' = rep(c('a', 'b', 'c'), 2), 'Date' = as.yearqtr(rep(c('2021 Q3', '2021 Q4'), each = 3)), 'Value' = 1:6)
Met = 'Per'
FN = function(y, class) ifelse(y == 0, 'y', ifelse(grepl('Per', class), paste0(y * 100, ' aa1'), paste0(y / 100, ' aa2')))
ggplot(Data, aes(x = Date, y = Value, fill = class)) +
    geom_bar(stat = 'identity', position = 'dodge', width = 0.1) +
    scale_y_continuous(labels = function(y) FN(y, Met))

With this I am getting below plot :

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In this plot all my Y-axis labels are 0, whereas I wanted to have "100 aa1" "200 aa1" "300 aa1" "400 aa1" "500 aa1" "600 aa1"

Any pointer what went wrong in my code will be very helpful.

>Solution :

If you mean paste0(Data$Value * 100, ' %') is like 200%, 400%,… then you may use scales::percent

ggplot(Data, aes(x = Date, y = Value, fill = class)) +
  geom_bar(stat = 'identity', position = 'dodge', width = 0.1) +
  scale_y_continuous(labels = scales::percent)

enter image description here

FN(Data$Value, Met)
[1] "100 %" "100 %" "100 %" "100 %" "100 %" "100 %"

sapply(Data$Value, function(x) FN(x, Met))
[1] "100 %" "200 %" "300 %" "400 %" "500 %" "600 %"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading