2

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.

For example:

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")

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"

4
  • 1
    Can you export Data instead? Commented Jun 21, 2018 at 15:25
  • Thanks for the tip! Yes I can but I am still wondering if it is possible to export the plot information somehow. Commented Jun 21, 2018 at 15:34
  • What exactly would you want to export? p is a ggplot object, not a data frame. If you want the data that was interpreted into geoms, use p$data, but this is likely the same as Data. If you want the dataframe that has positions and other information used in assembling geoms, use ggplot_build(p)$data Commented Jun 21, 2018 at 15:38
  • Maybe just dput(p)? Commented Jun 21, 2018 at 15:39

1 Answer 1

4
# 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.