【问题标题】:How to change y-axis to percentages with ggplot2 in R?如何在 R 中使用 ggplot2 将 y 轴更改为百分比?
【发布时间】:2018-10-05 03:15:13
【问题描述】:

我在 R 中有一个这样的代码段,用于绘图:

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

这对我有用,并产生如下内容:

基本上,(-2,+2) 从函数中的 minmax 参数的值传递到我的绘图。但问题是,我想要(-0.1%,+0.1%) 而不是 y 轴的 (-2.+2)。是否可以改变y轴的文字?

【问题讨论】:

标签: r ggplot2


【解决方案1】:

使用函数scale_y_continuous()。它有一个参数labels。您可以为此参数提供任何函数来将您拥有的标签转换为正确的标签。

如果您想将区间 [-2;2] 映射到 [-0.1; 0.1] 你可以做什么:

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

所以这个函数获取每个数字标签,除以 20 并转换为字符。

希望这就是您想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2018-12-15
    • 2021-08-03
    • 2015-09-30
    相关资源
    最近更新 更多