【问题标题】:Saving/Exporting ggplot2 data, not the plot itself保存/导出 ggplot2 数据,而不是绘图本身
【发布时间】:2018-06-21 15:23:07
【问题描述】:

有没有办法保存或导出用于绘图的 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”

【问题讨论】:

  • 你可以导出Data吗?
  • 感谢您的提示!是的,我可以,但我仍然想知道是否可以以某种方式导出情节信息。
  • 您到底想导出什么? pggplot 对象,而不是数据框。如果您想要解释成几何图形的数据,请使用p$data,但这可能与Data 相同。如果您想要具有用于组装几何图形的位置和其他信息的数据框,请使用ggplot_build(p)$data
  • 也许只是 dput(p)?

标签: r ggplot2


【解决方案1】:
# 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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    相关资源
    最近更新 更多