如何更改ggplot2中轴标签上的小数位数?

Pet*_*wis 40 r ggplot2

具体来说,这是在facet_grid中.已广泛搜索类似问题,但不清楚语法或它在哪里.我想要的是y轴上的每个数字在小数点后都有两位数,即使尾随的数字是0.这是scale_y_continuous或element_text中的参数还是......?

row1 <- ggplot(sector_data[sector_data$sector %in% pages[[x]],], aes(date,price)) + geom_line() +
  geom_hline(yintercept=0,size=0.3,color="gray50") +
  facet_grid( ~ sector) +
  scale_x_date( breaks='1 year', minor_breaks = '1 month') +
  scale_y_continuous( labels = ???) +
  theme(panel.grid.major.x = element_line(size=1.5),
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.title.y=element_blank(),
        axis.text.y=element_text(size=8),
        axis.ticks=element_blank()
  )
Run Code Online (Sandbox Code Playgroud)

Pie*_*une 49

从帮助中?scale_y_continuous,参数'labels'可以是一个函数:

标签之一:

  • 没有标签的NULL

  • waiver()用于由转换对象计算的默认标签

  • 给出标签的字符向量(必须与断点长度相同)

  • 将中断作为输入并将标签作为输出返回的函数

我们将使用最后一个选项,一个breaks作为参数的函数,并返回一个带有2位小数的数字.

#Our transformation function
scaleFUN <- function(x) sprintf("%.2f", x)

#Plot
library(ggplot2)
p <- ggplot(mpg, aes(displ, cty)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p + scale_y_continuous(labels=scaleFUN)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Rti*_*ist 25

"scales"包具有一些很好的格式化轴的功能.其中一个函数是number_format().所以你不必先定义你的功能.

library(ggplot2)
# building on Pierre's answer
p <- ggplot(mpg, aes(displ, cty)) + geom_point()
p <- p + facet_grid(. ~ cyl)

# here comes the difference
p + scale_y_continuous(
  labels = scales::number_format(accuracy = 0.01))

# the function offers some other nice possibilities, such as controlling your decimal 
# mark, here ',' instead of '.'
p + scale_y_continuous(
  labels = scales::number_format(accuracy = 0.01,
                                 decimal.mark = ','))
Run Code Online (Sandbox Code Playgroud)


小智 18

已更新,并number_format()已停用。使用label_number()。这也可以应用于百分比和其他连续比例(例如:label_percent()https://scales.r-lib.org/reference/label_percent.html)。

#updating Rtists answer with latest syntax from scales
library(ggplot2); library(scales)

p <- ggplot(mpg, aes(displ, cty)) + geom_point()
p <- p + facet_grid(. ~ cyl)

# number_format() is retired; use label_number() instead
p + scale_y_continuous(
  labels = label_number(accuracy = 0.01)
)

# for whole numbers use accuracy = 1
p + scale_y_continuous(
  labels = label_number(accuracy = 1)
)
Run Code Online (Sandbox Code Playgroud)