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

时间:2019-05-06 00:45:50

标签: r ggplot2

我正在尝试创建一个自定义函数以在ggplot中制作标签。例如,我可以在labels = scales::percent中使用scale_y_continuous()来使用百分号格式化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

3 个答案:

答案 0 :(得分: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-05-06创建

答案 1 :(得分:1)

根据所需的自定义程度,您仍然可以使用内置功能。例如,要获取带有三个小数位的百分比标签,可以执行以下操作:

library(ggplot2)
library(scales)

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

enter image description here

答案 2 :(得分:0)

啊,我设法弄清楚了。例如,下面的函数使我可以控制小数位数,同时也可以将值转换为百分比。

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))
相关问题