gpt4 book ai didi

r - 如何使ggplot2中的标题更美观?

转载 作者:行者123 更新时间:2023-12-02 08:36:32 25 4
gpt4 key购买 nike

我尝试在一些将在 .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

最佳答案

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 来轻松查找字体及其各自的名称。至于哪种字体“最漂亮”,这是非常主观的。

关于r - 如何使ggplot2中的标题更美观?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45446339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com