有时需要以两种或更多种语言创建一组数据的图表。当然可以手动输入ggplot图层来制作轴标题并引导图例标签发布就绪,但我想添加一些自动化来减少所需的代码量。
而不是添加图层来替换例如在axis标签中的变量名,我想将ggplot
调用包装在像replace_labels(plot,target_language)
这样的函数中,它会自动在我定义的字典中查找字符串。我写了一些几乎可以工作的代码,但问题是
scales
个对象等,并遇到标签宽度和布局等低级问题breaks = c("something", "or", "other")
等并重新创建绘图使用这些我还考虑替换data.frame
中的字符串,但这不是一个好的解决方案,因为我需要为每种语言编写ggplot
调用,这对我来说似乎是不必要的代码复制。任何建议如何优雅地国际化地块而不需要重写ggplot?
编辑:添加了由mdag02创建的略微修改的示例。
library(ggplot2)
language <- list(
fr_FR = list(
title = "Iris",
subtitle = "Le jeu de données connu",
caption = "French",
x = "Longueur des sépales, cm",
y = "Largeur des sépales, cm",
labels = c(setosa = "Setosa", versicolor = "Versicolor", virginica = "Virginica"),
legend = "Espèce",
labeller = function(variable,value) c(setosa = "Setosa", versicolor = "Versicolor", virginica = "Virginica")[value]
),
en_US = list(
title = "Iris",
subtitle = "The famous dataset",
caption = "English",
x = "Sepal Length, cm",
y = "Sepal Width, cm",
labels = c(setosa = "Setosa", versicolor = "Versicolor", virginica = "Virginica"),
legend = "Species",
labeller = function(variable,value) c(setosa = "Setosa", versicolor = "Versicolor", virginica = "Virginica")[value]
)
)
for (l in names(language)) {
message(l)
current <- language[[l]]
print(ggplot(data = subset(iris,
Species %in% c("virginica","versicolor")),
aes(x = Sepal.Length,
y = Sepal.Width)) +
geom_point() +
facet_grid(~Species,labeller = current$labeller)+
scale_colour_discrete(labels = current$labels,
name = current$legend) +
labs(
title = current$title,
subtitle = current$subtitle,
caption = paste(current$caption, format(Sys.Date(), "%Y-%m-%d")),
x = current$x,
y = current$y))
ggsave(file = paste0("iris_", l, ".png"), width = 21, height = 13, units = "cm", scale = 0.8)
}
我想这样做,以便我只需要将代码编写到geom_point
等geom并让计算机处理标签替换格式,例如scale_colour_discrete
喜欢这样:
ggplot(data = subset(iris,
Species %in% c("virginica","versicolor")),
aes(x = Sepal.Length,
y = Sepal.Width)) +
geom_point() +
facet_grid(~Species)
我可以通过将格式化图层封装在像myformats
之类的变量中来实现这个方向,但这种方法的一个缺点是,如果我想手动更改颜色,那么我需要重新引入标签替换代码因为我的手动格式会覆盖myformats
变量中的标签替换。
另外,如果我决定要编制Petal.Width
,那么我需要记住更改字典和ggplot
调用中的标签。我记得太可怕了,所以我再次把它留给电脑了。
答案 0 :(得分:2)
您可以遍历字符串列表:
library(ggplot2)
language <- list(
fr_FR = list(
title = "Iris",
subtitle = "Le jeu de données connu",
caption = "French",
x = "Longueur",
y = "Largeur"
),
en_US = list(
title = "Iris",
subtitle = "The famous dataset",
caption = "English",
x = "Length",
y = "Width"
)
)
for (l in names(language)) {
message(l)
current <- language[[l]]
ggplot(data = iris, aes(Sepal.Length, Sepal.Width)) +
geom_point() +
geom_smooth() +
labs(
title = current$title,
subtitle = current$subtitle,
caption = paste(current$caption, format(Sys.Date(), "%Y-%m-%d")),
x = current$x,
y = current$y)
ggsave(file = paste0("iris_", l, ".svg"), width = 21, height = 13, units = "cm", scale = 0.8)
}