2017-10-10 1 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가 제거 된 것을 알 수있다. 이 맥락에서 함께 그려 줄 수 있습니까 ??

들으

enter image description here

+0

이 모든 작업을 수행하려면'geom_bar'에서 막대 값을 15로 나눠야하고'limits'를 .1에서 시작하는 대신 0으로 내려야합니다 (막대가 0에서 시작됨). – aosmith

답변

2

두 번째 축의 변환이 제 2 축심을 만드는 데 사용되기 때문에 현재 문제가 실행중인 - 그것은 데이터에 영향을주지 않습니다. bar_data은 여전히 ​​원래 축에 플롯되어 있습니다. 원래 축은 한계 때문에 최대 0.5로 증가합니다. 이렇게하면 막대가 나타나지 않습니다.

동일한 범위에서 데이터를 표시하려면 막대 데이터가 포인트 데이터와 동일한 범위에 오도록 막대 데이터를 정규화해야합니다. 그런 다음 축 변환을 이 정규화를 실행 취소하여 적절한 눈금 레이블을 얻습니다. 그래서 같이 :

enter image description here

내가 축 특정 물건을 더 명확하게 당신의 종과 호각의 일부를 제거,하지만 당신은 할 수 있어야 :

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

이렇게하면 다음과 같은 플롯을 제공합니다 다시 문제없이 다시 추가하십시오. 그러나 두 개의 노트 :

  • 두 번째 축은 주 축의 1-1 변환에 의해 생성되므로 변형시 동일한 제한을 포함해야합니다. 막대가 0이되어야하는 경우 기본 축에는 변환되지 않은 0의 아날로그가 포함되어야합니다.

  • 데이터 정규화와 축 변환이 서로 축약되어 축이 플롯 할 값과 일치하도록하십시오.