如何像图片中那样将y轴变成百分比形式?我可以改变y轴范围,但无法将其转换为百分比。
使用:
+ scale_y_continuous(labels = scales::percent)
或者,为百分比指定格式参数:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(labels = percent
命令自ggplot2版本2.2.1起已过时)
原则上,您可以将任何重新格式化函数传递给labels
参数:
+ scale_y_continuous(labels = function(x) paste0(x*100, "%")) # Multiply by 100 & add %
或者
+ scale_y_continuous(labels = function(x) paste0(x, "%")) # Add percent sign
可重现的例子:
library(ggplot2)
df = data.frame(x=seq(0,1,0.1), y=seq(0,1,0.1))
ggplot(df, aes(x,y)) +
geom_point() +
scale_y_continuous(labels = function(x) paste0(x*100, "%"))
ggplot2
和scales
包可以实现这一点:
y <- c(12, 20)/100
x <- c(1, 2)
library(ggplot2)
library(scales)
myplot <- qplot(as.factor(x), y, geom="bar")
myplot + scale_y_continuous(labels=percent)
似乎 stat()
选项已被移除,导致出现错误信息。尝试这样做:library(scales)
myplot <- ggplot(mtcars, aes(factor(cyl))) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(labels=percent)
myplot
以上来自 @Deena 的函数修改方法,可以让标签更加灵活多变。例如,我的ggplot中有一个计数变量的分母是140,我就可以使用她的示例进行修改:
scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))
library(scales)
。 - Akshay Gaurscales::percent(accuracy = 1)
无法工作的原因是*_format()
版本创建了一个函数,而不是percent()
单独创建的内容,这是正确的吗? - MokeEire