3

We are using dplot in rCharts (using the dimple library) to try to create a bubble chart in R Shiny. This is all working well but we are having trouble assigning specific colours to specific bubbles (or "Channel" in the code below). We have managed to specify a set of colours using defaultColors but these are assigned to the Channels randomly, not in the way we've specified!

Can anyone help us get the colo(u)rs mapped correctly?

output$BubbleChart2 <- renderChart2({
    Channel <- c('TV','Radio','Press')
    Spend <- c(100000,50000,20000)
    Revenue <- c(500000,100000,30000)
    df <- data.frame(Channel,Spend,Revenue)
    df$ROI <- (df$Revenue/df$Spend)
    r2 <-dPlot(x="Revenue",y="ROI",type="bubble",groups="Channel",z="Spend",data=df,width=750)
    r2$defaultColors("#!d3.scale.ordinal().range(['#C2E588','#FDC382','#FC9A8F']).domain(['TV','Radio','Press'])!#")
    r2$xAxis(type = "addMeasureAxis")
    r2$yAxis(type = "addMeasureAxis")
    r2$zAxis(type = "addMeasureAxis")
    r2$legend( x = 200,
               y = 7,
               width = 400,
               height = 20,
               horizontalAlign = "center" )    
    return(r2)

1 Answers1

1

I am not familiar with rCharts, but according to the comments in this SO question, the ordering of colors is in descending order of the count.

So what you can do is: add a color column to your data.frame and then sort the colors in descending order by the column you are plotting by.

It is just a workaround though, you should probably submit an issue on github.

Quick example:

library(rCharts)

Channel <- c('TV','Radio','Press')
Spend <- c(100000,50000,20000)
Revenue <- c(500000,100000,30000)
df <- data.frame(Channel,Spend,Revenue)
df$ROI <- (df$Revenue/df$Spend)
df$Colors <- c("'#C2E588'","'#FDC382'","'#FC9A8F'")

col_order <- df[order(-Revenue), "Colors"] %>% paste(collapse = ",")
r2 <- dPlot(x="Revenue",y="ROI",type="bubble",groups="Channel",z="Spend",data=df,width=750)
r2$defaultColors(sprintf("#!d3.scale.ordinal().range([%s])!#", col_order))
r2

df$Revenue <- c(5000,100000,30000)

r3 <- dPlot(x="Revenue",y="ROI",type="bubble",groups="Channel",z="Spend",data=df,width=750)
r3$defaultColors(sprintf("#!d3.scale.ordinal().range([%s])!#", col_order))
r3

r2:

r2

r3:

r3

GyD
  • 3,902
  • 2
  • 18
  • 28