Search code examples
rplotlyscatter-plotmarkersr-plotly

How to adjust plotly marker colors to match ordered categories in R?


Using plotly in R, I would like the categories to be different colors (preferably pre-chosen by me) in order of # of songs. Here's what I tried:

salesplot <-plot_ly(producersales, type="scatter", x=Producer, y=SalesPerSong, color=c('20+ songs', '11 songs','8-10 songs','5-7 songs', '3-4 songs', '2 songs'), size=SalesPerSong, mode="markers")
## Sample of my data
head(producersales)
               Producer NoOfSongs TotalSales SalesPerSong  SongRange
1             Timbaland        24    3446852       143619  20+ songs
2            Just Blaze        23    3134585       136286  20+ songs
3            Kanye West        20    3338410       166920  20+ songs
4 Jerome "J-Roc" Harmon        11    1165000       105909   11 songs
5          The Neptunes        11    1419877       129080   11 songs
6               No I.D.         9    1437008       159668 8-10 songs

The problem is that when I print salesplot, all the markers are in one color (2 songs). Also, if I try using color=SongRange, the legend is not in the order that I need.


Solution

  • Are you looking for something like this?

    #order factor like you want
    producersales$SongRange  <- factor(producersales$SongRange , 
                                       levels = c("8-10songs", "11songs", "20+songs"))
    
    #select colour you want
    cols <- c("red", "blue", "black")
    #plot
    salesplot <- plot_ly(producersales, 
                         type = "scatter", 
                         x = Producer, 
                         y = SalesPerSong, 
                         color = SongRange,
                         colors = cols, 
                         mode = "markers")
    salesplot