I want to know how to save a ggplot graph object into the r environment so it doesn't require dataset. I've displayed some example code that illustrates my problem below.
I want to object to display the graph after removing the base dataset used to create the graph.
--
# Sample graph for analyses
## loads package(s)
# ---- NOTE: for package tidyverse
if(!require(tidyverse)){install.packages("tidyverse")}
# ---- NOTE: for package ggplot2
if(!require(ggplot2)){install.packages("ggplot2")}
## filters diamonds data so we have the first 300 rows
diamonds_top_300 <- head(diamonds, n = 300)
## creates graph
diamonds_top_300_graph <-
ggplot(
diamonds_top_300,
aes(
x =
(diamonds_top_300[["carat"]])
,
y =
(diamonds_top_300[["price"]])
)
) +
geom_point(
aes(
colour =
(diamonds_top_300[[("color")]])
),
)
## displays head of original data and then runs graph object
# ---- NOTE: shows head of data
head(diamonds_top_300)
# ---- NOTE: displays graph
diamonds_top_300_graph
# ---- NOTE: DOES WORK
## removes original dataset and then runs graph object
# ---- NOTE: removes appropriate object
remove(diamonds_top_300)
# ---- NOTE: displays graph
diamonds_top_300_graph
# ---- NOTE: DOES NOT WORK