I would like to extract the labels and the colors assigned to the data points (X,Y). I have tried to extract them using the approach mentioned in this solution.
head(dataPlot)
# Source: local data frame [6 x 3]
# Groups: EFOValue [2]
#
# # A tibble: 6 x 3
# X Y EFOValue
# <dbl> <dbl> <chr>
# 1 0.505115 0.348486 adipose tissue
# 2 0.365520 0.414446 adipose tissue
# 3 0.365520 0.414446 adipose tissue
# 4 0.526531 0.341508 adrenal gland
# 5 0.526531 0.341508 adrenal gland
# 6 0.412384 0.385316 adrenal gland
p2 <- ggplot(dataPlot, aes(x=X, y=Y, color=EFOValue)) + geom_point()
g2 <- ggplot_build(p2)
data.frame(colours = unique(g2$data[[1]]["colour"]),
label = levels(g2$plot$data[, g2$plot$labels$colour])
The sample code worked as expected with the sample dataset, iris
.
For this dataset dataPlot
, the output plot is as expected.
However, I have noticed that the g2$plot
is empty in g2
object and so the extraction of the values was not possible. Could please advise what might be the reasons for this and how to overcome the error in this ggplot approach? Is there any other alternative to do this: either by passing colors to the plotting system by assigning colors to each level.