2016-08-19 14 views
4

有沒有什麼辦法可以在沒有定義序列的情況下在ggplot中設置斷點步長。例如:改變軸斷點而不定義序列 - ggplot

x <- 1:10 
y <- 1:10 

df <- data.frame(x, y) 

# Plot with auto scale 
ggplot(df, aes(x,y)) + geom_point() 

# Plot with breaks defined by sequence 
ggplot(df, aes(x,y)) + geom_point() + 
    scale_y_continuous(breaks = seq(0,10,1)) 

# Plot with automatic sequence for breaks 
ggplot(df, aes(x,y)) + geom_point() + 
    scale_y_continuous(breaks = seq(min(df$y),max(df$y),1)) 

# Does this exist? 
ggplot(df, aes(x,y)) + geom_point() + 
    scale_y_continuous(break_step = 1) 

你可能會說我是懶惰,但也出現了幾次,我不得不改變我的seqminmax限制由於添加的錯誤吧。所以我只想說...使用x的中斷大小,並帶有自動縮放限制。

回答

3

您可以定義自己的函數以傳遞到休息參數。將工作你的情況的一個例子是

f <- function(y) seq(floor(min(y)), ceiling(max(y))) 

然後

ggplot(df, aes(x,y)) + geom_point() + scale_y_continuous(breaks = f) 

enter image description here

您可以修改它傳送符,例如步驟

f <- function(k) { 
     step <- k 
     function(y) seq(floor(min(y)), ceiling(max(y)), by = step)  
} 

然後

ggplot(df, aes(x,y)) + geom_point() + scale_y_continuous(breaks = f(2)) 

將在2創建y軸與蜱,4,...,10等

您可以通過編寫自己的規模進一步採取這種功能

my_scale <- function(step = 1, ...) scale_y_continuous(breaks = f(step), ...) 

,只是這樣稱呼它

ggplot(df, aes(x,y)) + geom_point() + my_scale() 

我認爲不應該破壞任何東西,但你永遠無法確定:)

+0

尼斯一個,那真是棒極了。謝謝 – Pete900