programing

ggplot2에서 글꼴 변경

projobs 2021. 1. 14. 08:03
반응형

ggplot2에서 글꼴 변경


옛날 옛적에를 ggplot2사용하여 글꼴 windowsFonts(Times=windowsFont("TT Times New Roman"))을 변경했습니다. 이제 이걸 떨쳐 낼 수가 없어요.

설정하려고 년 family=""ggplot2 theme()나는 다른 글꼴 가족들과 함께 아래의 MWE을 컴파일로 글꼴의 변화를 생성 할 수없는 것.

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
        ggtitle("Fuel Efficiency of 32 Cars") +
        xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
        theme(text=element_text(size=16, 
#       family="Comic Sans MS"))
#       family="CM Roman"))
#       family="TT Times New Roman"))
#       family="Sans"))
        family="Serif"))


print(a)
print("Graph should have refreshed")

R은 경고를 반환 font family not found in Windows font database하지만 이것이 정상이며 문제가 아니라고 말하는 튜토리얼이 있습니다 (다시 찾을 수 있다면 여기에서 링크를 업데이트 할 것입니다). 또한 내 그래프가 한때 arial 또는 helvitica 유형 글꼴을 사용했기 때문에 어떻게 든 한 번에 작동했습니다. 나는 이것이 초기 마이그레이션 중에도 항상 현재의 경고라고 생각합니다.

최신 정보

windowsFonts()내 출력을 실행할 때

$ serif [1] "TT Times New Roman"

$ sans [1] "TT Arial"

$ mono [1] "TT Courier New"

그러나 이것은 내가 실행 한 후 font_import()이므로 내 글꼴이 올바른 위치에 저장되지 않는다는 결론을 내릴 수 있습니다. font_import()요청 을 실행 한 코드는 실제로 다음을 사용하여 라이브러리를로드합니다.

LocalLibraryLocation <- paste0("C:\\Users\\",Sys.getenv("USERNAME"),"\\Documents","\\R\\win-library\\3.2");
    .libPaths(c(LocalLibraryLocation, .libPaths()))

제 생각에 초기화 단계를 놓쳤습니다.

명령으로 사용 가능한 글꼴을 볼 수 있습니다 windowsFonts(). 예를 들어, 이것을보기 시작했을 때 내 모습은 다음과 같습니다.

> windowsFonts()
$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

extraFont 패키지를 설치하고 다음과 font_import같이 실행 한 후 (약 5 분 소요) :

library(extrafont)
font_import()
loadfonts(device = "win")

나는 더 많은 것을 가지고 있었다-논쟁의 여지가 너무 많고, 확실히 여기에 나열하기에는 너무 많다.

그런 다음 코드를 시도했습니다.

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="Comic Sans MS"))
print(a)

이것을 산출 :

여기에 이미지 설명 입력

최신 정보:

다음 코드 스 니펫 을 사용하여 family매개 변수에 필요한 글꼴 이름을 찾을 수 있습니다 element_text.

> names(wf[wf=="TT Times New Roman"])
[1] "serif"

그리고:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="serif"))
print(a)

수율 : 여기에 이미지 설명 입력


또 다른 옵션은 showtext더 많은 유형의 글꼴 (TrueType, OpenType, Type 1, 웹 글꼴 등)과 더 많은 그래픽 장치를 지원하고 Ghostscript와 같은 외부 소프트웨어를 사용하지 않는 패키지를 사용하는 것입니다.

# install.packages('showtext', dependencies = TRUE)
library(showtext)

일부 Google 글꼴 가져 오기

# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")

현재 검색 경로에서 글꼴로드 showtext

# Check the current search path for fonts
font_paths()    
#> [1] "C:\\Windows\\Fonts"

# List available font files in the search path
font_files()    
#>   [1] "AcadEref.ttf"                                
#>   [2] "AGENCYB.TTF"                           
#> [428] "pala.ttf"                                    
#> [429] "palab.ttf"                                   
#> [430] "palabi.ttf"                                  
#> [431] "palai.ttf"

# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")

font_families()
#> [1] "sans"         "serif"        "mono"         "wqy-microhei"
#> [5] "Montserrat"   "Roboto"       "Palatino"

## automatically use showtext for new devices
showtext_auto() 

플롯 : showtextRStudio 내장 그래픽 장치에서 제대로 작동하지 않으므로 Windows 그래픽 장치를 열어야 함

# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
windows()

myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"

library(ggplot2)

a <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text = element_text(size = 16, family = myFont1)) +
  annotate("text", 4, 30, label = 'Palatino Linotype',
           family = myFont3, size = 10) +
  annotate("text", 1, 11, label = 'Roboto', hjust = 0,
           family = myFont2, size = 10) 

## On-screen device
print(a) 

## Save to PNG 
ggsave("plot_showtext.png", plot = a, 
       type = 'cairo',
       width = 6, height = 6, dpi = 150)  

## Save to PDF
ggsave("plot_showtext.pdf", plot = a, 
       device = cairo_pdf,
       width = 6, height = 6, dpi = 150)  

## turn showtext off if no longer needed
showtext_auto(FALSE) 

파티 에 늦었지만 shinyapps.io ggplotsshiny내부에 사용자 지정 글꼴을 추가하려는 사람들에게는이 기능이 흥미로울 수 있습니다 .

다음을 수행 할 수 있습니다.

  1. 에 넣어 사용자 정의 글꼴 www디렉토리 : 예 IndieFlower.ttf로부터 여기
  2. 여기 에서 단계를 따르십시오

그러면 app.R파일 내부에 다음과 같은 상단 섹션이 있습니다.

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

전체 예제 앱은 여기 에서 찾을 수 있습니다 .

참조 URL : https://stackoverflow.com/questions/34522732/changing-fonts-in-ggplot2

반응형