2017-07-24 85 views
0

我想在我的ggplot的頂部添加第二個x軸。第一個x軸顯示一年的第幾天,第二個x軸顯示根據第一個x軸日期的月份。我嘗試了sec.axis,但沒有奏效。在ggplot中添加sec.axis

b Alt 
148 1300 
122 1300 
130 1300 
250 2000 
300 2000 
244 2000 

    MonthId <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Agu", 
"Sep", 
"Oct", "Nov", "Dec") 
FirstDay <- c(1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335,365) 
MiddleDay <- c(16, 45, 75, 105, 136, 166, 197, 228, 258, 289, 319, 350) 
g.b <- ggplot(CDD, aes(factor(Alt), b)) 
g.b+ 
    scale_x_continuous(breaks = unique(MiddleDay), 
      sec.axis = sec_axis(~ ., breaks = unique(MiddleDay))) 
+0

不知道,如果你可以繪製一個次要軸線的DISCR規模。 [This](https://codedump.io/share/jTG0XXtcl08D/1/duplicating-discrete-axis-in-ggplot2)可能會有幫助。 – Jimbou

+0

在'aes(factor(Alt),b)'中,您正在繪製Alt x軸。那麼你用scale_x_continuous使用FirstDay? –

回答

3

我不確定我是否理解根據您的數據和說明進行繪圖。對於在二級繪製一年的主x軸的日,月,你可以使用這樣的事情:

假設你有以下數據:

MonthId <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Agu", "Sep", "Oct", "Nov", "Dec") 
MiddleDay <- c(16, 45, 75, 105, 136, 166, 197, 228, 258, 289, 319, 350) 
b <- c(148, 122, 130, 250, 300, 244, 148, 122, 130, 250, 300, 244) 
df <- data.frame(MonthId, MiddleDay, b) 

然後用sec_axis(~ . ...與期望breakslevels

q = ggplot() + geom_line(data = df, aes(y = b, x = MiddleDay)) 
q + scale_x_continuous("day of the year", 
sec.axis = sec_axis(~ . , breaks = df$MiddleDay, labels = df$MonthId , name = "Month")) 

enter image description here