保存/导出ggplot2数据,而不是图本身 [英] Saving/Exporting ggplot2 data, not the plot itself
本文介绍了保存/导出ggplot2数据,而不是图本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以保存或导出用于绘图的ggplot数据?我不是说图像本身,而是信息r存储在全球环境中.
Is there a way to save or export the ggplot data used for plotting? I do not mean the image itself but the information r stores in the global environment.
例如:
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"
What I want is to export "p" as csv or txt. Is this possible? I tried "write.table(p)" but I get the error: "cannot coerce class "c("gg", "ggplot")" to a 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")
这篇关于保存/导出ggplot2数据,而不是图本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文