r - 保存/导出 ggplot2 数据,而不是绘图本身

标签 r ggplot2

有没有办法保存或导出用于绘图的 ggplot 数据?我指的不是图像本身,而是存储在全局环境中的信息。

例如:

Data <- data.frame(
    X = sample(1:10),
    Y = sample(c("yes", "no"), 10, replace = TRUE))

p <- ggplot(data=Data, aes(x=Y, y=X)) +
     geom_bar(stat="identity")

我想要的是将“p”导出为csv或txt。这可能吗?我尝试了“write.table(p)”,但收到错误:“无法将类“c(“gg”,“ggplot”)”强制到 data.frame”

最佳答案

# Create some data and plot
library(tidyverse)
p <- as.data.frame(matrix(rnorm(20), ncol = 2, 
                     dimnames = list(1:10, c("x", "y")))) %>%
  mutate(group = as.factor(round((mean(y) - y)^2))) %>%
  ggplot(aes(x, y, color = group)) +
  geom_point() +
  theme_bw()

# you can't write it as txt or csv:
glimpse(p)

#List of 9
# $ data       :'data.frame':   10 obs. of  3 variables:
#  ..$ x    : num [1:10] -0.612 0.541 1.038 0.435 -0.317 ...
#  ..$ y    : num [1:10] 0.2065 0.9322 0.0485 -0.3972 -0.048 ...
#  ..$ group: Factor w/ 3 levels "0","1","2": 1 1 1 2 1 1 3 1 3 1
# $ layers     :List of 1

# but you can write it as Rds
write_rds(p, "./myplot.Rds")
# and read and plot afterwards:
read_rds("./myplot.Rds")

random plot

关于r - 保存/导出 ggplot2 数据,而不是绘图本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50972180/

相关文章:

r - 将环境中的所有 ggplot2 图存储在列表中

r - 在我自己的服务器上部署一个应用程序,地址中没有端口号

r - ggplot2 & facet_wrap - 消除小平面之间的垂直距离

r - ggplot2:x 轴刻度之间的条形图

r - ggplot2 - 饼图 - 值标签倒序

c++ - R - ggplot2 使用什么作为其绘图后端?

r - 计算两个字符串之间的匹配

r - 如何通过根据名称而不是索引选择一系列列和行来切片数据框?

重复函数中的前一行直到满足 if 语句

r - 将文本添加到与条件匹配的ggplot geom_jitter点