Search code examples
rplotlycolor-coding

3dscatter plot for trading data


I'm experimenting for quit some time with the tables of the trade.sqlite3 database. I came up with a combined table of the import and export table.

A csv-file of the table can be downloaded here :

Added a virus scan of the file as well

str of the table to get an idea how it looks like :

Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 300 obs. of 4 variables:
$ year : num 2002 2002 2002 2002 2002 ...
$ category: Factor w/ 10 levels "0--Food And Live Animals",..: 1 2 3 4 5 6 7 8 9 10 ...
$ value : num 4.94e+08 2.88e+08 9.40e+08 4.96e+07 7.76e+06 ...
$ type : Factor w/ 2 levels "Exp","Imp": 1 1 1 1 1 1 1 1 1 1 ...

Now I want to plot this table using plot_ly.

I came up with the following idea :

library(plotly)
total_val <- read.csv("Total_Value")
plot_ly(data = total_val, x = total_val$year, 
y = total_val$value, z = total_val$category, color = total_val$category, 
stroke = total_val$category, type = "scatter3d" )

I still fight with some problems :
- I want to indicate if a marker is of type import or export.
- Using the color code as I did produces the following warning :

n too large, allowed maximum for palette Set2 is 8
Returning the palette you asked for with that many colors

There are 10 categorys and I need to display them all. Is there a better way to do this despite color coding?

Any other opinions to make the plot more informative are highly recommended.


Solution

  • following this I came up with a solution to plot with different shapes the Imp and Exp. The color issue is as easy as specifying the colors using the colors argument.

    total_val$markers <- ifelse(total_val$type == "Exp", "circle", "diamond")
    library(plotly)
    p <- plot_ly(data = total_val, x = ~year, 
            y = ~value, z = ~category, color = ~category,
            colors = rainbow(length(levels(total_val$category))),
            text = ~paste('category:', category, '<br>value:', value, '<br>year:', year,
                          '<br>type:', type)) %>%
      add_markers() %>%
      layout(scene = list(xaxis = list(title = 'year'),
                          yaxis = list(title = 'Value'),
                          zaxis = list(title = 'Category')))
    
    p <- plotly_build(p)
    
    for (i in 1:length(p$x$data)) {
      values <- total_val$markers[total_val$category == levels(total_val$category)[i]]
      p$x$data[[i]]$marker$symbol <- values
    }
    p
    

    Hope this helps!