如何使用ggplot更改轴上数字的格式?

时间:2012-07-23 09:33:09

标签: r ggplot2

我正在使用R和ggplot绘制一些数据的散点图,一切都很好,除了y轴上的数字是用计算机样式指数格式出来的,即4e + 05,5e + 05等。这显然是不可接受的,所以我想把它显示为500,000,400,000等等。获得正确的指数表示法也是可以接受的。

情节的代码如下:

p <- ggplot(valids, aes(x=Test, y=Values)) +
  geom_point(position="jitter") +
  facet_grid(. ~ Facet) +
  scale_y_continuous(name="Fluorescent intensity/arbitrary units") +
  scale_x_discrete(name="Test repeat") +
  stat_summary(fun.ymin=median, fun.ymax=median, fun.y=median, geom="crossbar")

任何帮助都非常感激。

5 个答案:

答案 0 :(得分:106)

另一种选择是使用包scales格式化您的轴刻度标签,然后添加

 scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = comma)

到你的ggplot声明。

如果您不想加载包,请使用:

scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = scales::comma)

答案 1 :(得分:51)

我还发现了另一种方法,可以提供适当的x10(上标)5&#39;轴上的符号。我在这里发帖,希望对某些人有用。我从here得到了代码,所以我声称没有归功于它,这正确地归功于Brian Diggs。

fancy_scientific <- function(l) {
     # turn in to character string in scientific notation
     l <- format(l, scientific = TRUE)
     # quote the part before the exponent to keep all the digits
     l <- gsub("^(.*)e", "'\\1'e", l)
     # turn the 'e+' into plotmath format
     l <- gsub("e", "%*%10^", l)
     # return this as an expression
     parse(text=l)
}

然后您可以将其用作

ggplot(data=df, aes(x=x, y=y)) +
   geom_point() +
   scale_y_continuous(labels=fancy_scientific) 

答案 2 :(得分:40)

x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)

答案 3 :(得分:15)

我在这里游戏的时间已经晚了,但是在其他人想要一个简单的解决方案的情况下,我创建了一组可以被称为的函数:

 ggplot + scale_x_continuous(labels = human_gbp)

它为您提供x或y轴的人类可读数字(或者通常是任何数字)。

您可以在此处找到这些功能:Github Repo 只需将函数复制到脚本中即可调用它们。

答案 4 :(得分:8)

我发现Jack Aidley的建议答案很有用。

我想抛出另一种选择。假设你有一个包含许多小数字的系列,并且你想确保轴标签写出完整的小数点(例如5e-05 - > 0.0005),然后:

NotFancy <- function(l) {
 l <- format(l, scientific = FALSE)
 parse(text=l)
}

ggplot(data = data.frame(x = 1:100, 
                         y = seq(from=0.00005,to = 0.0000000000001,length.out=100) + runif(n=100,-0.0000005,0.0000005)), 
       aes(x=x, y=y)) +
     geom_point() +
     scale_y_continuous(labels=NotFancy)