Reputation: 343
How can I reverse the process the code for ggplot? Suppose for any dataset, I have made a ggplot. Now how can I reverse this process. i.e., from a ggplot I want to make a matrix/table.
Let's say my dataset looks like this:
ID A B Act
1 12 12 A
1 13 18 B
1 15 11 A
1 12 12 A
1 13 10 c
1 16 17 A
1 18 16 A
1 17 17 B
1 20 11 c
I used this command for ggplot:
library("ggplot2")
ggplot(df, aes(y = A, x = B, colour = Act), pch = 17) +
geom_point()
Now, once I have a ggplot, How can I produce a table out of it using ggplot?
Upvotes: 1
Views: 383
Reputation: 19061
You can save your ggplot in a local variable (e.g. plot
) and use the data
property of this variable (e.g. plot$data
):
library("ggplot2")
df <- data.frame(
ID = rep(1, 9),
A = c(12, 13, 15, 12, 13, 16, 18, 17, 20),
B = c(12, 18, 11, 12, 10, 17, 16, 17, 11),
Act = c("A", "B", "A", "A", "C", "A", "A", "B", "C"))
plot <- ggplot(df, aes(y = A, x = B, colour = Act), pch = 17) + geom_point()
data <- plot$data
data
# ID A B Act
# 1 1 12 12 A
# 2 1 13 18 B
# 3 1 15 11 A
# 4 1 12 12 A
# 5 1 13 10 C
# 6 1 16 17 A
# 7 1 18 16 A
# 8 1 17 17 B
# 9 1 20 11 C
You can observe the full ggplot
structure via str(plot)
:
str(plot)
# List of 9
# $ data :'data.frame': 9 obs. of 4 variables:
# ..$ ID : num [1:9] 1 1 1 1 1 1 1 1 1
# ..$ A : num [1:9] 12 13 15 12 13 16 18 17 20
# ..$ B : num [1:9] 12 18 11 12 10 17 16 17 11
# ..$ Act: Factor w/ 3 levels "A","B","C": 1 2 1 1 3 1 1 2 3
# $ layers :List of 1
# ..$ :Classes 'proto', 'environment' <environment: 0x00000000187ac768>
# $ scales :Reference class 'Scales' [package "ggplot2"] with 1 fields
# ..$ scales: list()
# ..and 21 methods, of which 9 are possibly relevant:
# .. add, clone, find, get_scales, has_scale, initialize, input, n, non_position_scales
# $ mapping :List of 3
# ..$ x : symbol B
# ..$ y : symbol A
# ..$ colour: symbol Act
# $ theme : list()
# $ coordinates:List of 1
# ..$ limits:List of 2
# .. ..$ x: NULL
# .. ..$ y: NULL
# ..- attr(*, "class")= chr [1:2] "cartesian" "coord"
# $ facet :List of 1
# ..$ shrink: logi TRUE
# ..- attr(*, "class")= chr [1:2] "null" "facet"
# $ plot_env :<environment: R_GlobalEnv>
# $ labels :List of 3
# ..$ x : chr "B"
# ..$ y : chr "A"
# ..$ colour: chr "Act"
# - attr(*, "class")= chr [1:2] "gg" "ggplot"
Upvotes: 3