首页 > 解决方案 > 使用自定义标签函数在 ggplot 中标记 y 轴

问题描述

我正在尝试创建一个自定义函数来在ggplot. 例如,我可以使用labels = scales::percentwithinscale_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

标签: rggplot2

解决方案


像这样。

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 包(v0.2.1)于 2019 年 5 月 6 日创建


推荐阅读