0

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.

Prradep
  • 5,506
  • 5
  • 43
  • 84
  • Can you show an example please, as using the iris dataset, and the answer from your link gives the expected result – user20650 Jul 13 '17 at 13:23
  • ahhh ... it doesnt work with tibbles. Convert data to a dataframe or use `label = levels(g$plot$data[[g$plot$labels$colour]])` – user20650 Jul 13 '17 at 13:27
  • It did not work with data frame as well. – Prradep Jul 13 '17 at 13:28
  • does for me, so can you add an example please - say using the iris dataset – user20650 Jul 13 '17 at 13:29
  • @user20650 With iris dataset, it works fine as mentioned in the solution. But, it doesn't replicate with my dataset. – Prradep Jul 13 '17 at 13:38
  • 1
    praddep - can you share some data ? ps I added an example using the iris dataset as a tibble , and then converting to a dataframe at the r chat site. https://chat.stackoverflow.com/rooms/25312/r-public – user20650 Jul 13 '17 at 13:56

1 Answers1

0

Posting it as an answer as per moderator's request so that future users can benefit from the answer.


I have found the issue. The issue is that the variable EFOValue used for coloring is not a factor variable. So, the levels() function results an empty slot(or no desired output).

Prradep
  • 5,506
  • 5
  • 43
  • 84