简体   繁体   English

使用自定义标签功能在ggplot中标记y轴

[英]Use custom labeling function for labeling y axis in ggplot

I'm trying to create a custom function for making labels within ggplot . 我正在尝试创建一个自定义函数来在ggplot制作标签。 For example, I can use labels = scales::percent within scale_y_continuous() to format the y axis using percentage sign. 例如,我可以在scale_y_continuous()使用labels = scales::percent使用百分号格式化y轴。 However, I would like more control over the labeling function. 但是,我希望对标签功能有更多的控制。

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

The documentation for scale_y_continuous() suggests that it is possible to create a custom function that can take in breaks and output labels, but there is no demonstration of this in the documentation. scale_y_continuous()的文档建议可以创建一个可以包含中断和输出标签的自定义函数,但是在文档中没有对此进行演示。

labels One of: 标签之一:

 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 

Like this. 像这样。

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)

Created on 2019-05-06 by the reprex package (v0.2.1) reprex软件包 (v0.2.1)创建于2019-05-06

Depending on how much customization you need, you might still be able to use the built-in functions. 根据所需的自定义程度,您可能仍然可以使用内置功能。 For example, to get percent labels with three decimal places, you could do: 例如,要获取带有小数点后三位的百分比标签,您可以执行以下操作:

library(ggplot2)
library(scales)

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

在此处输入图片说明

Ah, I managed to figure it out. 啊,我设法弄清楚了。 For example, the function below allows me to control the number of decimal places while also converting values into percentages. 例如,下面的函数使我可以控制小数位数,同时也可以将值转换为百分比。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM