r - 使用自定义标签函数在 ggplot 中标记 y 轴
问题描述
我正在尝试创建一个自定义函数来在ggplot
. 例如,我可以使用labels = scales::percent
withinscale_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
解决方案
像这样。
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 日创建
推荐阅读
- angular - 无法将路由器注入 HttpInterceptor (Angular 7)
- druid - 如何在druid中查询数据?
- sql-server - 从sql server加载数据到redshift(增量)
- javascript - 导致一个标签点击另一个标签
- spring-integration - Spring integration kafka - 监听器没有响应 - 我怎么能找出原因?
- java - 如何在重定向标准输出时从 Java 控制台安全地读取密码?
- java - 无法启动 Gwt 项目
- node.js - 如何将 MongoDB 添加到 Docker 容器?
- c# - 同时创建两个同名信号量
- c++ - QProcess 不从单独的线程读取输入