字体族在ggplot中无法更改

6

我的图表可以工作,但是我无法改变字体家族。即使我能够改变其他方面,比如颜色、大小和对齐方式,字体始终保持默认。

这是我的代码:

ggplot(data = SeattleJuly17Data,
       aes(x = Price, y = SatisfactionScore, col = RoomType)) +
    geom_point() +
    xlim(0,500) +
    geom_smooth() +
    ggtitle("Satisfaction Trends by Price and Room Type") +
    theme(plot.title = element_text(family = "Calibri",
                                    size=15,
                                    color="Red",
                                    hjust = 0.5)) +
    xlab("Price per Night") +
    ylab("Guest Satisfaction Score")

1
你可能需要使用专门用于嵌入字体的库,例如 extrafontshowtext - camille
1个回答

3
您可以使用extrafont包来选择您想要的字体。
library(ggplot2)
library(ggpmisc)

### Use more updated dev version on Github
# install.packages("remotes")
# remotes::install_github("wch/extrafont")
library(extrafont)

### Run this one only ONCE to import all fonts to R
# font_import(prompt = FALSE)

# or import only specific font
font_import(pattern = "DejaVu", prompt = FALSE)

# if the font is not in default search path e.g. `C:/Windows/Fonts/`
myfontPath <- "C:/Users/xxx/Downloads/Fonts/"
font_import(pattern = "DejaVu",
            paths = myfontPath,
            recursive = TRUE,
            prompt = FALSE)

### Load fonts
# Options: "all", "pdf", "postscript", or "win"
loadfonts(device = "all")

### Choose the desired font
myFont <- "DejaVu Sans Mono"
# Can also override the default sans, mono or serif fonts
windowsFonts(mono  = myFont)
windowsFonts()

### Plot
set.seed(666)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3*df$x + rnorm(100, sd = 40)

formula1 <- y ~ x

ggplot(data = df, aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, formula = formula1) +
  stat_poly_eq(aes(label = paste(..eq.label.., sep = "~~~")), 
               family = myFont, # specify font
               label.x.npc = "right", label.y.npc = 0.15,
               eq.with.lhs = "italic(hat(y))~`=`~",
               eq.x.rhs = "~italic(x)",
               formula = formula1, parse = TRUE, size = 6) +
  stat_poly_eq(aes(label = paste(..rr.label.., sep = "~~~")), 
               family = myFont,
               label.x.npc = "right", label.y.npc = "bottom",
               formula = formula1, parse = TRUE, size = 6) +
  theme_bw(base_size = 20, 
           base_family = myFont) # specify font

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接