2017-11-21 2 views
2

ggplot의 여백에 화살표를 그려 넣으려고합니다. 내가 읽은 것으로부터, 당신은 플롯 클리핑을 꺼야합니다. 그러나 그렇게하면 그래프에있는 선분이 삭제됩니다.ggplot 클리핑을 해제하면 선분이 삭제됩니다.

library(ggplot2) 
library(ggrepel) 
library(grid) 

#----------------- Fake data practice --------------------- # 

mydata <- data.frame(Labels = letters[1:14], 
        X_Values = seq(1, 14, 1), 
        Y_Values = rnorm(14, mean = 0, sd = 1), 
        Influence = seq(1, 14, 1)) 


mydata$Influencer <- factor(ifelse(mydata$Influence <= 3, 1, 0)) 

# --- Get min/max from data and use to set range at -1to1 or -2to2 

chartMax <- ifelse(min(mydata$Y_Values) < -1 | max(mydata$Y_Values) > 1, 2, 1) 
chartMin <- ifelse(chartMax == 1, -1, -2) 

yTitle = "Some Title" 
# --- Label setting, if greater than 0 nudge up, else nudge down 

mydata$Nudger <- ifelse(mydata$Y_Values >= 0, .1, -.1) 


p <- ggplot(mydata, aes(x = X_Values, y = Y_Values, group = Influencer)) + 
     geom_point(aes(size = Influencer, color = Influencer), shape = 18) + 
     geom_segment(x = 0, xend = 14, y = 0, yend = 0, color = "red", linetype = "dashed", size = 1.2, alpha = .5) + 
     geom_text_repel(aes(x = X_Values, y = Y_Values, label = Labels), 
         box.padding = .4, 
         point.padding = .2, 
         nudge_y = .1) + 
     scale_color_manual(values = c("grey", "blue")) + 
     scale_size_manual(values = c(4, 6)) + 
     scale_y_continuous(name = "", limits = c(chartMin, chartMax)) + 
     scale_x_continuous(name = yTitle, 
          limits = c(1, 15), 
          breaks = c(2,13), 
          labels = c("Lower", "Higher")) + 
     theme_classic() + theme(plot.margin = unit(c(1,3,1,2), "lines"), 
           legend.position="none", 
           axis.ticks.x=element_blank(), 
           axis.text.x = element_text(face = "bold"), 
           axis.title = element_text(face = "bold"), 
           axis.line.x = element_line(color = "blue" 
                  ,size = 1 
                  ,arrow = 
                  arrow(length = unit(0.5, "cm"), 
                    ends = "both"))) + 
     annotation_custom(
      grob = linesGrob(arrow=arrow(type="open", ends="both", length=unit(0.5, "cm")), gp=gpar(col="blue", lwd=2)), 
      xmin = -1.4, xmax = -1.4, ymin = chartMin, ymax = chartMax 
     ) 

p 
# Here it works and you see the red dashed line 

# Turn off panel clipping 
gt <- ggplot_gtable(ggplot_build(p)) 
gt$layout$clip[gt$layout$name == "panel"] <- "off" 
grid.draw(gt) 

이상적으로, 나는 여백의 y 축과 함께 실행되는 파란색 화살표를 원한다. 나는 그것을 가지고 있다고 생각하지만, 내 안의 그래프를 따라 움직이는 빨간 점선을 풀 수는 없다.

+0

를 중 하나에 의해 또는의 gtable 객체를 후 처리 사용자 지정 축 Grob https://stackoverflow.com/a/27149233/471093 – baptiste

답변

1

나는 을 설명 할 수 없다. (버그 인 것 같아서, here 문제를 제기하는 것이 좋습니다.) 문제는 라인 알파와 관련되어 있음을 확인할 수 있습니다. 우리가 라인을 삭제하지 않고 geom_segment 다음 클리핑 = 오프 작품에서 alpha = 0.5 인수를 삭제할 경우, 대체 경로가 패널 외부에 화살표를 추가하는 것입니다

enter image description here

관련 문제