如何在ggplot2中制作更美观的字幕?

时间:2017-08-01 19:37:55

标签: r ggplot2 r-markdown

我试图在一些将在.rmd文件中显示的图中添加标题,但添加的标题不是很美观。如果我只是在.rmd文件而不是绘图中包含标题,那将会更好看。有没有办法让字幕在ggplot2中看起来更漂亮?

library(ggplot2)

data <- data.frame(col = c("left", "right"),
                   row = c("first", "second", "third", "fourth"),
                   x = rep.int(1,4),
                   y = rep.int(1,4))
data$col <- as.character(data$col)
data$row <- as.character(data$row)

caption <- paste(strwrap("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", width = 170), collapse = "\n")

ggplot(data = data) +
  facet_grid(row~col) +
  labs(x = "x", y = "y", caption = caption) +
  theme_bw(base_size = 16) +
  theme(legend.position = "bottom",
        plot.margin = margin(15, 15, 15, 15),
        plot.caption = element_text(size = 10, hjust = 0))

我添加的字幕 The captions that I added

1 个答案:

答案 0 :(得分:7)

library(ggplot2)

data <- data.frame(col = c("left", "right"),
                   row = c("first", "second", "third", "fourth"),
                   x = rep.int(1,4),
                   y = rep.int(1,4))
data$col <- as.character(data$col)
data$row <- as.character(data$row)

caption <- paste(strwrap("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", width = 170), collapse = "\n")

library(extrafont)
font_import(prompt=FALSE) # This installs the fonts. Only run this once! 
loadfonts(device="win") # Loads the fonts

fonts_lookup = t(data.frame(windowsFonts())) # font lookup table

ggplot(data = data) +
  facet_grid(row~col) +
  labs(x = "x", y = "y", caption = caption) +
  theme_bw(base_size = 16) +
  theme(legend.position = "bottom",
        plot.margin = margin(15, 15, 15, 15),
        plot.caption = element_text(size = 12, hjust = 0.5,
                                    family = "Garamond", color = "blue", face = "bold"))

enter image description here

可能同时更改字体系列,颜色或面部或全部?您可以参考这个问题的字体:Changing fonts in ggplot2extrafont包允许您安装比现有字体多得多的字体。 windowsFonts()让您检查已加载的字体。我创建了fonts_lookup以便于查找字体及其各自的名称。至于哪种字体是“最漂亮的”,这是非常主观的。