【问题标题】:How do I change the number of decimal places on axis labels in ggplot2?如何更改 ggplot2 中轴标签上的小数位数?
【发布时间】:2016-08-02 13:43:40
【问题描述】:

具体来说,这是在 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()
  )

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    ?scale_y_continuous 的帮助中,参数“标签”可以是一个函数:

    标签之一:

    • 无标签为 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)
    

    【讨论】:

      【解决方案2】:

      “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 = ','))
      

      【讨论】:

        【解决方案3】:

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

        #updating Rtists answer with latest syntax from scales
        library(tidyverse); 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)
        )
        

        【讨论】:

          猜你喜欢
          • 2013-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多