Reputation: 510
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
Upvotes: 0
Views: 506
Reputation: 33782
The issue here is that you are using aes
incorrectly. Instead of, for example:
aes(x = diamonds_top_300[["carat"]], ...)
You should use just the column name:
aes(x = carat, ...)
In the first case, ggplot
is trying to calculate something using the data frame. That data is lost when the data frame is removed.
In the second, the data is saved as part of the diamonds_top_300_graph
object, so the data is not lost.
So your code should read:
diamonds_top_300_graph <-
ggplot(
diamonds_top_300,
aes(
x = carat,
y = price,
)
) +
geom_point(
aes(
colour = color
)
)
Upvotes: 2