Ggplot2에 자막을 추가하는 방법(예제 3개)


다음 방법을 사용하여 ggplot2의 플롯에 자막을 추가할 수 있습니다.

방법 1: 자막 추가

 p+
  labs(title=' My Title ', subtitle=' My Subtitle ')

방법 2: 여러 줄로 된 자막 추가

 p+
  labs(title=' My Title ', subtitle=' My Subtitle Line1\nLine2\nLine3 ')

방법 3: 사용자 정의 글꼴로 자막 추가

 p+
  labs(title=' My Title ', subtitle=' My Subtitle Line1\nLine2\nLine3 ') +
  theme(plot. subtitle =element_text(size= 18 , face=' italic ', color=' red '))

다음 예에서는 R의 다음 데이터 프레임을 사용하여 실제로 각 메서드를 사용하는 방법을 보여줍니다.

 #create data frame
df <- data. frame (hours=c(1, 2, 2, 3, 4, 6, 7, 7, 8, 9),
                 score=c(76, 77, 75, 79, 84, 88, 85, 94, 95, 90))

#view data frame
df

   hours score
1 1 76
2 2 77
3 2 75
4 3 79
5 4 84
6 6 88
7 7 85
8 7 94
9 8 95
10 9 90

예 1: ggplot2에 자막 추가

다음 코드는 ggplot2의 산점도에 한 줄짜리 자막을 추가하는 방법을 보여줍니다.

 library (ggplot2)

#create scatter plot with subtitle on one line
ggplot(df, aes(x=hours, y=score)) +
  geom_point(size= 2 ) +
  labs(title=' Hours Studied vs. Exam Score ',
       subtitle=' Data Collected in 2022 ') 

플롯 제목 바로 아래에 한 줄짜리 자막이 추가되었습니다.

예 2: ggplot2에 여러 줄 자막 추가

다음 코드는 ggplot2의 산점도에 여러 줄 자막을 추가하는 방법을 보여줍니다.

 library (ggplot2)

#create scatter plot with subtitle on multiple lines
ggplot(df, aes(x=hours, y=score)) +
  geom_point(size= 2 ) +
  labs(title=' Hours Studied vs. Exam Score ',
       subtitle=' Data Collected in 2022\nUniversity A Exam Scores ') 

ggplot2의 여러 줄 자막

개행 구문( \n )을 사용하면 여러 줄로 된 자막을 만들 수 있습니다.

예 3: 사용자 정의 글꼴로 자막 추가

다음 코드는 ggplot2의 theme() 함수를 사용하여 사용자 정의 글꼴 크기, 스타일 및 색상으로 자막을 추가하는 방법을 보여줍니다.

 library (ggplot2)

#create scatter plot with subtitle that has customized font
ggplot(df, aes(x=hours, y=score)) +
  geom_point(size= 2 ) +
  labs(title=' Hours Studied vs. Exam Score ',
       subtitle=' Data Collected in 2022\nUniversity A Exam Scores ') +
  theme(plot. subtitle =element_text(size= 18 , face=' italic ', color=' red ')) 

맞춤 글꼴이 포함된 ggplot2 자막

이제 자막의 글꼴 크기는 18이고 기울임꼴 스타일과 빨간색이 되었습니다.

참고 : 굵은 글꼴 스타일을 사용하려면 Face=’bold’를 사용할 수도 있습니다.

추가 리소스

다음 튜토리얼에서는 ggplot2에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

ggplot2 플롯에 범례를 추가하는 방법
ggplot2에서 글꼴 크기를 변경하는 방법
ggplot2에서 범례를 제거하는 방법
ggplot2에서 축 레이블을 회전하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다