ggplot2-플롯 외부에 주석 달기
샘플 크기 값을 플롯의 포인트와 연결하고 싶습니다. geom_text
점 근처에 숫자를 배치하는 데 사용할 수 있지만 이것은 지저분합니다. 줄거리의 바깥 쪽 가장자리를 따라 정렬하는 것이 훨씬 더 깔끔 할 것입니다.
예를 들어 다음과 같습니다.
df=data.frame(y=c("cat1","cat2","cat3"),x=c(12,10,14),n=c(5,15,20))
ggplot(df,aes(x=x,y=y,label=n))+geom_point()+geom_text(size=8,hjust=-0.5)
이 플롯을 생성합니다.
나는 다음과 같은 것을 더 선호합니다.
나는 두 번째 플롯 및 사용을 만들 수 있다는 사실을 알고 계실 것 grid.arrange
(라 이 게시물을 )하지만 y 축으로 정렬하는 textGrobs의 간격을 결정하는 지루한 것입니다. 이 작업을 수행하는 더 쉬운 방법이 있습니까? 감사!
두 번째 플롯을 그릴 필요는 없습니다. 를 사용 annotation_custom
하여 플로팅 영역 내부 또는 외부에 grob을 배치 할 수 있습니다 . grobs의 위치는 데이터 좌표와 관련이 있습니다. "5", "10", "15"가 "cat1", "cat2", "cat3"과 일치한다고 가정하면 textGrob의 수직 위치가 처리됩니다. 세 개의 textGrob의 y 좌표는 세 데이터 포인트의 y 좌표. 기본적으로 ggplot2
플로팅 영역에 그롭을 클리핑하지만 클리핑을 재정의 할 수 있습니다. grob을위한 공간을 만들기 위해 관련 마진을 넓혀야합니다. 다음 (ggplot2 0.9.2 사용)은 두 번째 플롯과 유사한 플롯을 제공합니다.
library (ggplot2)
library(grid)
df=data.frame(y=c("cat1","cat2","cat3"),x=c(12,10,14),n=c(5,15,20))
p <- ggplot(df, aes(x,y)) + geom_point() + # Base plot
theme(plot.margin = unit(c(1,3,1,1), "lines")) # Make room for the grob
for (i in 1:length(df$n)) {
p <- p + annotation_custom(
grob = textGrob(label = df$n[i], hjust = 0, gp = gpar(cex = 1.5)),
ymin = df$y[i], # Vertical position of the textGrob
ymax = df$y[i],
xmin = 14.3, # Note: The grobs are positioned outside the plot area
xmax = 14.3)
}
# Code to override clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)
이제 ggplot2 3.0.0에서는 간단 coord_cartesian(clip = 'off')
합니다. 아래 예제와 같이를 호출하여 플롯에서 클리핑을 비활성화 할 수 있기 때문 입니다.
# Generate data
df <- data.frame(y=c("cat1","cat2","cat3"),
x=c(12,10,14),
n=c(5,15,20))
# Create the plot
ggplot(df,aes(x=x,y=y,label=n)) +
geom_point()+
geom_text(x = 14.25, # Set the position of the text to always be at '14.25'
hjust = 0,
size = 8) +
coord_cartesian(xlim = c(10, 14), # This focuses the x-axis on the range of interest
clip = 'off') + # This keeps the labels from disappearing
theme(plot.margin = unit(c(1,3,1,1), "lines")) # This widens the right margin
기반의 단순한 솔루션 grid
require(grid)
df = data.frame(y = c("cat1", "cat2", "cat3"), x = c(12, 10, 14), n = c(5, 15, 20))
p <- ggplot(df, aes(x, y)) + geom_point() + # Base plot
theme(plot.margin = unit(c(1, 3, 1, 1), "lines"))
p
grid.text("20", x = unit(0.91, "npc"), y = unit(0.80, "npc"))
grid.text("15", x = unit(0.91, "npc"), y = unit(0.56, "npc"))
grid.text("5", x = unit(0.91, "npc"), y = unit(0.31, "npc"))
참고 URL : https://stackoverflow.com/questions/12409960/ggplot2-annotate-outside-of-plot
'Development Tip' 카테고리의 다른 글
Javascript + Regex = 반복 할 사항 없음 오류? (0) | 2020.12.08 |
---|---|
스토리 보드를 통해로드되면 뷰가 어떻게 초기화됩니까? (0) | 2020.12.08 |
Pandas 시리즈의 히스토그램 값 (0) | 2020.12.08 |
브라우저 간 확대 방지 (0) | 2020.12.08 |
"이미있는 프로그램 유형"은 무엇을 의미합니까? (0) | 2020.12.08 |