tinker
tinker

Reputation: 3424

How to change y-axis to percentages with ggplot2 in R?

I have a code segment like this in R, which I use for plotting:

plot_bar <- function(x, y, min, max, color = plot_colors[2]) {
  p <- ggplot(data.frame(as.integer(x), y)) +
    geom_bar(aes(x, y), stat = "identity", position = "dodge", fill = color) + ylim(min, max) + 
    theme_light() + theme(text = element_text(size = 25), axis.title.x = element_blank(), axis.title.y = element_blank())

  return(p)
}

This works for me, and produces something like this:

enter image description here

Basically, the (-2,+2) is passed to my plot from values of min and max arguments in the function. But the problem is that, instead of (-2.+2) for y-axis I want to have (-0.1%,+0.1%). Is it possible to change the text in the y-axis?

Upvotes: 2

Views: 6149

Answers (1)

Pavel Filatov
Pavel Filatov

Reputation: 596

Use function scale_y_continuous(). It have an argument labels. You can provide any function to this argument to convert labels you have to proper ones.

In your case if you want to map interval [-2;2] to [-0.1; 0.1] what you could do:

p <- ggplot(...) + geom_*(...)
p + scale_y_continuous(labels = function(x) paste0(x/20, "%"))

So this function gets each numeric label, divides it by 20 and convert into character.

Hope that's what you are looking for.

Upvotes: 4

Related Questions