2016-08-02 215 views
10

具體來說,這是在facet_grid中。已經廣泛搜索類似的問題,但不清楚語法或它的去向。我想要的是,y軸上的每個數字在小數點後有兩位數,即使尾數是0。這是scale_y_continuous或element_text中的參數還是...?如何更改ggplot2中軸標籤上的小數位數?

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() 
) 

回答

19

從幫助?scale_y_continuous,參數 '標籤' 可以是一個函數:

標籤之一:

  • NULL爲沒有標籤

  • 放棄()爲由變換對象計算的默認標籤

  • 一個特徵向量給標籤(必須是相同的長度,斷裂)

  • ,是以休息作爲輸入並返回標籤作爲輸出

我們將使用最後一個選項的函數,一個將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) 

enter image description here