2

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?

tinker
  • 2,884
  • 8
  • 23
  • 35
  • [this](https://stackoverflow.com/questions/27433798/how-to-change-y-axis-range-to-percent-from-number-in-barplot-with-r?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) is a similar post with relevant responses. – apax Apr 24 '18 at 18:48
  • 1
    See `?scale_y_continuous`. To format as a percent, pass `labels = scales::percent`. It looks like you also want a transformation, though, for which you'll need to show some data. – alistaire Apr 24 '18 at 18:50
  • Possible duplicate of [How to change y axis range to percent (%) from number in barplot with R](https://stackoverflow.com/questions/27433798/how-to-change-y-axis-range-to-percent-from-number-in-barplot-with-r) – divibisan Apr 24 '18 at 18:51

1 Answers1

3

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.

Pavel Filatov
  • 586
  • 3
  • 6