2017-05-12 180 views
0

我想要繪製兩條線具有相同的x軸但不同的y軸。geom_line與不同的y軸刻度

在這裏讀對話geom_bar + geom_line: with different y-axis scale? 爲了在同一個圖上繪製visit_time和item_bought,我創建了以下代碼。我已成功地創建右側的副軸,但是我不能夠增添色彩的傳說和y軸標籤(一個一個左的作品,而不是右邊)

temp <- data.frame 
(day = c("2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05", "2017-01-06" ,"2017-01-07" ,"2017-01-08", "2017-01-09", "2017-01-10", "2017-01-11", "2017-01-12", "2017-01-13", "2017-01-14", "2017-01-15", "2017-01-16", "2017-01-17", "2017-01-18", "2017-01-19", "2017-01-20", "2017-01-21", "2017-01-22", "2017-01-23"), 
        items =c(33,34,12,31,26,45,15,20,30,44,31,48,18,4,12,38,1,3,3,1,6,7,20), 
        visit_time =c(2, 1, 11, 12, 16, 20, 10, 6, 19, 22, 18, 22, 15, 1, 9, 23, 2, 4, 5, 2, 12, 4, 22)) 
temp$day <- as.Date(temp$day, "%Y-%m-%d") 

       p1 = ggplot(temp, aes(day, items)) + geom_line(colour="darkblue", size = 1) + 
        ylab("items") + 
        theme(legend.position="none",axis.text.x = element_text(angle = 90, hjust = 0), 
         panel.background = element_rect(fill = NA), 
         panel.grid = element_blank()) 

       p2 = ggplot(temp, aes(day, visit_time)) + geom_line(colour="darkorange3", size =1) + ylab("visit_time") + 
        theme(legend.position="none",axis.text.x = element_text(angle = 90, hjust = 0), 
         panel.background = element_rect(fill = NA), 
         panel.grid = element_blank()) 

       g1 <- ggplot_gtable(ggplot_build(p1)) 
       g2 <- ggplot_gtable(ggplot_build(p2)) 

       # overlap the panel of 2nd plot on that of 1st plot 
       pp <- c(subset(g1$layout, name == "panel", se = t:r)) 
       g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t, 
            pp$l, pp$b, pp$l) 

       # axis tweaks 
       ia <- which(g2$layout$name == "axis-l") 
       ga <- g2$grobs[[ia]] 
       ax <- ga$children[[2]] 
       ax$widths <- rev(ax$widths) 
       ax$grobs <- rev(ax$grobs) 
       ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm") 
       g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1) 
       g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b) 

       # draw it 
       grid.draw(g) 

我不知道這是最有效的方法,所以我很高興有另一種方法。只要我在兩側和顏色圖例上有兩條線和明確的y軸名稱。

非常感謝提前。

+2

[這是典型的問題](https://stackoverflow.com/questions/3099219/plot-with-2-y-axes-one-y-axis-on-the-left-and-另一個-y軸 - 上的右)。簡短的回答是,你不容易,因爲哈德利認爲這是一個壞主意,正如他在他的回答中解釋的那樣。儘管如此,他已經使轉換成爲可能。 Celcius和Fahrenheit。正如你發現的那樣,它可以通過網格黑客入侵,但它需要一些工作。 – alistaire

回答

2
dat <- temp %>% gather(y, val, items:visit_time) 

ggplot(dat, aes(day, val, colour=y)) + 
    geom_line(data=dat %>% filter(y=="items")) + 
    geom_line(data=dat %>% filter(y=="visit_time"), aes(y=val*2)) + 
    scale_y_continuous(sec.axis= sec_axis(~./2, name="visit_time")) 

enter image description here

添加scale_colour_manual如果您發現默認太令人不快調整顏色。

scale_colour_manual(values = c("darkblue", "darkorange3"))