【问题标题】:Use custom labeling function for labeling y axis in ggplot使用自定义标签函数在 ggplot 中标记 y 轴
【发布时间】:2019-05-06 00:45:49
【问题描述】:

我正在尝试创建一个自定义函数来在ggplot 中制作标签。例如,我可以在scale_y_continuous() 中使用labels = scales::percent 来使用百分号格式化y 轴。但是,我想对标签功能进行更多控制。

> mydf <- data.frame(a = 1:9,
+                    b = 1:9 / 10)
> mydf
  a   b
1 1 0.1
2 2 0.2
3 3 0.3
4 4 0.4
5 5 0.5
6 6 0.6
7 7 0.7
8 8 0.8
9 9 0.9
> ggplot(mydf) + geom_point(aes(x = a, y = b)) + scale_y_continuous(labels = scales::percent)

scale_y_continuous() 的文档建议可以创建一个可以接收中断和输出标签的自定义函数,但文档中没有对此进行演示。

标签之一:

NULL for no labels

waiver() for the default labels computed by the transformation object

A character vector giving labels (must be same length as breaks)

A function that takes the breaks as input and returns labels as output

【问题讨论】:

  • 您能否举例说明您希望最终标签的外观?据我记得,您只需要创建一个函数,该函数接受一个数字向量(“原始”中断值),并返回一个相同长度的字符向量。
  • @Marius 是的,你是对的,我想多了。

标签: r ggplot2


【解决方案1】:

像这样。

library(tidyverse)

mydf <- data.frame(a = 1:9, b = 1:9 / 10)

mylabels <- function(breaks){
    labels <- sprintf("%i%%", breaks*100) # make your labels here
    return(labels)
}

ggplot(mydf) + 
    geom_point(aes(x = a, y = b)) + 
    scale_y_continuous(labels = mylabels)

由reprex package (v0.2.1) 于 2019 年 5 月 6 日创建

【讨论】:

    【解决方案2】:

    根据您需要的自定义程度,您可能仍然可以使用内置功能。例如,要获得三位小数的百分比标签,您可以这样做:

    library(ggplot2)
    library(scales)
    
    ggplot(mydf, aes(a, b)) + 
      geom_point() + 
      scale_y_continuous(labels=percent_format(accuracy=0.001))
    

    【讨论】:

      【解决方案3】:

      啊,我设法弄明白了。例如,下面的函数允许我控制小数位数,同时还将值转换为百分比。

      my_func <- function(x, decimals = 1) {
        fmt <- paste0("%.", decimals, "f") # eg "%.3f"
        num_string <- sprintf(fmt, 100*x)
        final_string <- paste0(num_string, "%")
        return(final_string)
      }
      
      ggplot(mydf) + 
        geom_point(aes(x = a, y = b)) + 
        scale_y_continuous(labels = function(i) my_func(i, decimals = 0))
      

      【讨论】:

      • 您可以使用内置的scales::percent_format() 函数来执行此操作。 labels = percent_format(accuracy = 1) 舍入到最接近的 1,labels = percent_format(accuracy = 0.5) 舍入到最接近的 0.5,等等。有关详细信息和示例,请参阅 ?percent_format 帮助页面。
      • 这只是一个简单的例子来演示。我希望针对我的特定问题使用更具体的格式(调整填充、比例、舍入等的简单方法)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多