如何从R ggplot图像获取SVG字符串?

问题描述 投票:0回答:1

在 R 中,假设我有一个

ggplot
对象,如下面教程中的
p
所示:

library(ggplot2)
data <- data.frame(
        day = as.Date("2017-06-14") - 0:364,
        value = runif(365) + seq(-140, 224)^2 / 10000
)
p <- ggplot(data, aes(x=day, y=value)) +
        geom_line() +
        xlab("")

我不想看到图像,也不想将其保存到文件中。我想要的是获取一个作为该图像的 SVG 的字符串,而不执行这些操作。这可能吗?

r ggplot2 svg
1个回答
0
投票

你可以使用这样的东西:

graph_file <- tempfile(fileext = ".png")
on.exit(unlink(graph_file), add = TRUE)

png(filename = graph_file,
    width = 500, height = 500, units = "px", 
    bg = "white",  
    res = NA, 
)

p
dev.off()

readBin(graph_file, "raw", n=file.info(graph_file)$size) |> 
    intToUtf8() 
© www.soinside.com 2019 - 2024. All rights reserved.