-2

I want to plot a figure where my third dimension (Z) is defined by a color hex which is defined by the make up of three values.

I have already converted three values into a hex using rgb(). I now have a data frame which has the x and y values as numbers and a z column with a bunch of hex values.

Is there a way to create a plot where each point is colored by the hex value, whether that is by creating a heat map in plotly or using geom_raster/geom_tile in ggplot2.

If there is another package that I could use thats fine too.

Here is some code to show what I have done thus far

library(dplyr)
set.seed(1)

x <- c(1,1,1,2,2,2,3,3,3)
y <- c(1,2,3,1,2,3,1,2,3)
cap_1 <- runif(9,0,10)
cap_2 <- runif(9,0,10)
cap_3 <- runif(9,0,10)
df <- data.frame(x,y,cap_1,cap_2, cap_3)

I convert the capacity (cap_1 to cap_3) into percentages and then create a color hex based on the primary colors from the percentages

df <- df %>%
    mutate(cap_sum = rowSums(df[3:5])) %>%
    mutate(cap_1_p = cap_1/cap_sum) %>%
    mutate(cap_2_p = cap_2/cap_sum) %>%
    mutate(cap_3_p = cap_3/cap_sum) %>%
    mutate(z = rgb(cap_1_p, cap_2_p,cap_3_p))

I have tried plotting it as a heat map unsuccessfully:

library(plotly)
fig <- plot_ly(df, x='x', y='y', z='z', 
           type = "heatmap")
fig
  • 1
    Can you share code and data to make your problem [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – markus Oct 16 '18 at 19:33
  • I made some edits to the questions with code. The question is really about the last lines of code – Simon Sandler Oct 17 '18 at 02:43

1 Answers1

0

Here's an approach going through ggplot and on to ggplotly:

g <- ggplot(df, aes(x,y, fill = z)) + 
  geom_tile() +
  scale_fill_identity()
plotly::ggplotly(g)

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53