2017-10-10 482 views
1

我遇到了一個問題,即如前一篇文章how-to-use-facets-with-a-dual-y-axis-ggplot中所述,在藉助第二軸功能的情況下使用兩個不同的數據。ggplot2中使用雙y軸(第二軸)

我正在嘗試使用geom_pointgeom_bar,但由於geom_bar數據範圍不同,因此在圖上未顯示。

這是我試過的;

point_data=data.frame(gr=seq(1,10),point_y=rnorm(10,0.25,0.1)) 
bar_data=data.frame(gr=seq(1,10),bar_y=rnorm(10,5,1)) 

library(ggplot2) 



sec_axis_plot <- ggplot(point_data, aes(y=point_y, x=gr,col="red")) + #Enc vs Wafer 
geom_point(size=5.5,alpha=1,stat='identity')+ 
geom_bar(data=bar_data,aes(x = gr, y = bar_y, fill = gr),stat = "identity") + 
scale_y_continuous(sec.axis = sec_axis(trans=~ .*15, 
             name = 'bar_y',breaks=seq(0,10,0.5)),breaks=seq(0.10,0.5,0.05),limits = c(0.1,0.5),expand=c(0,0))+ 

facet_wrap(~gr, strip.position = 'bottom',nrow=1)+ 
theme_bw() 

因爲可以看出bar_data被刪除。在這種情況下可以將它們一起繪製?

THX

enter image description here

+0

爲了完成這一切工作,您需要在'geom_bar'中將您的bar值除以15,並使您的'limits'降至0而不是從.1開始(因爲bar從0開始)。 – aosmith

回答

2

你遇到了問題在這裏,因爲第二軸的改造僅用於創建第二個軸 - 其對數據沒有影響。您的bar_data仍然被繪製在原始軸上,由於您的限制,它只會上升到0.5。這可以防止條出現。

爲了使數據顯示在同一範圍內,必須對條形數據進行歸一化處理,使其與點數據位於同一範圍內。然後,軸轉換必須撤消這種規範化,以便您得到適當的刻度標籤。像這樣:

# Normalizer to bring bar data into point data range. This makes 
# highest bar equal to highest point. You can use a different 
# normalization if you want (e.g., this could be the constant 15 
# like you had in your example, though that's fragile if the data 
# changes). 
normalizer <- max(bar_data$bar_y)/max(point_data$point_y) 


sec_axis_plot <- ggplot(point_data, 
         aes(y=point_y, x=gr)) + 

    # Plot the bars first so they're on the bottom. Use geom_col, 
    # which creates bars with specified height as y. 
    geom_col(data=bar_data, 
      aes(x = gr, 
       y = bar_y/normalizer)) + # NORMALIZE Y !!! 

    # stat="identity" and alpha=1 are defaults for geom_point 
    geom_point(size=5.5) + 

    # Create second axis. Notice that the transformation undoes 
    # the normalization we did for bar_y in geom_col. 
    scale_y_continuous(sec.axis = sec_axis(trans= ~.*normalizer, 
             name = 'bar_y')) + 
    theme_bw() 

這給你以下情節:

enter image description here

我刪除了你的一些花裏胡哨,使特定軸的東西更清楚,但你應該能夠添加它沒有問題。一些註釋雖然如下:

  • 請記住,第二軸是由主軸的1-1變換創建的,因此請確保它們在變換下覆蓋相同的極限。如果你有條應該歸零,那麼主軸應該包含零變換的模擬。

  • 確保數據標準化和軸變換相互撤銷,以便軸與您繪製的值保持一致。