gpt4 book ai didi

r - 使用自定义标签函数在 ggplot 中标记 y 轴

转载 作者:行者123 更新时间:2023-12-02 16:57:09 24 4
gpt4 key购买 nike

我正在尝试创建一个自定义函数,用于在 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() 的文档建议可以创建一个自定义函数来接受中断和输出标签,但文档中没有对此进行演示。

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

最佳答案

像这样。

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 创建于 2019-05-06 (v0.2.1)

关于r - 使用自定义标签函数在 ggplot 中标记 y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com