R 如何使用ggplot2在比例上添加单位?

R 如何使用ggplot2在比例上添加单位?,r,ggplot2,R,Ggplot2,我目前正在使用ggplot创建图表 我想知道如何在我的刻度上添加单位(比如后缀) 这是电子秤的代码行: mean <- mean(DTA[, 2]) # column two mean from my data frame scale_x_continuous(breaks = c(mean -10, mean - 5, mean, mean + 5, mean + 10)) 谢谢正如评论所述,有几种方法可以做到这一点。在任何情况下,您都需要使用缩放*\u连续(或缩放*\u离散)中的标

我目前正在使用ggplot创建图表

我想知道如何在我的刻度上添加单位(比如后缀)

这是电子秤的代码行:

mean <- mean(DTA[, 2]) # column two mean from my data frame

scale_x_continuous(breaks = c(mean -10, mean - 5, mean, mean + 5, mean + 10))

谢谢

正如评论所述,有几种方法可以做到这一点。在任何情况下,您都需要使用
缩放*\u连续
(或
缩放*\u离散
)中的
标签
参数来指定格式。最简单的方法是使用
scales
软件包,该软件包提供了一些易于使用的格式化功能,如
percent
percent\u格式

ggplot2
中,可以通过两种方式指定格式。手动标签,例如,
labels=c(“30%,“40%,…)
和作为一个函数的
labels=percent
。下面我说明了如何使用
mtcars
数据集来实现这一点

data("mtcars")
mtcars$RatioOfOptimalMpg <- with(mtcars, mpg / max(mpg)) 
scales::percent(mtcars$RatioOfOptimalMpg)[1:6]
#[1] "61.9%" "61.9%" "67.3%" "63.1%" "55.2%" "53.4%"
library(ggplot2)
ggplot(data = mtcars, aes(x = hp, y = RatioOfOptimalMpg)) + 
    geom_point() + 
    labs(y = "% of best mpg observed") + 
    scale_y_continuous(labels = scales::percent)
或者类似地创建一个函数,如
scales::percent
,它将为您进行格式化

addPercent <- function(x, ...) #<== function will add " %" to any number, and allows for any additional formatting through "format".
    format(paste0(x, " %"), ...)
ggplot(data = mtcars, aes(x = hp, y = RatioOfOptimalMpg * 100)) + 
    geom_point() + 
    labs(y = "% of best mpg observed") + 
    scale_y_continuous(labels = addPercent)

addPercent使用scales包,检查
percent\u格式
number\u格式(后缀='%')
(我想这就是代码)您想要指定
标签
而不是
中断
。我的图表必须与其他数据(%、克、百分之重)一起重复使用,我只想这样更改单位。(我知道您的代码以百分比的形式转换数据,是真的吗?)。在我的例子中,我只想在休息后加上“%”。示例在大约50秒内添加。您的评估是正确的<代码>比例::百分比
基本上乘以
100
并向输出中添加“%”。相反,您可以使用
粘贴(…,sep=“”)
粘贴0(…)
合并数字和百分号。这对我使用
past0
单位效果很好
ggplot(data = mtcars, aes(x = hp, y = RatioOfOptimalMpg * 100)) + 
    geom_point() + 
    labs(y = "% of best mpg observed") + 
    scale_y_continuous(labels = paste0(RatioOfOptimalMpg * 100, " %"))
addPercent <- function(x, ...) #<== function will add " %" to any number, and allows for any additional formatting through "format".
    format(paste0(x, " %"), ...)
ggplot(data = mtcars, aes(x = hp, y = RatioOfOptimalMpg * 100)) + 
    geom_point() + 
    labs(y = "% of best mpg observed") + 
    scale_y_continuous(labels = addPercent)