Pryore
Pryore

Reputation: 520

Plotly - Ordering & Colouring by Factor Variables and in a Bar Chart

Hi,

I'm using plotly to generate an ordered bar chart, which would show customer segments on the X axis and frequency count on the Y axis. The problem is, I also want to set the colour according to the frequency of the segments.

I'm using a dataframe with 93 observations with the same structure as this:

   df <- data.frame(
         Segments = c("Pete", "Gary", "TopNews"...),
         Frequency = c(4,2,5...)
         )

The problem

As expected, R automatically recognized the 'Segments' variable as a factor. When I plotted the graph the first time, it ordered itself (as expected). I used the following code:

  plot_ly(Segments2, y = ~Var1, x = ~Freq, type = "bar", orientation = 'h')

So this wasn't a problem, but it become an issue when I tried to tie the colour of bars to the 'Freq' variable, i.e.:

    plot_ly(Segments2, y = ~Var1, x = ~Freq, type = "bar", color = ~Freq, orientation = 'h')

Of course, R printed the following error:

‘range’ not meaningful for factors

So all in all, my question is: how do I colour such an ordered plotly bar chart using frequency as the sequential colour?

enter image description here

Upvotes: 0

Views: 1093

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31679

You could add your frequency to color of the marker object.

enter image description here

library(plotly)

df <- data.frame(
  Segments = c("Pete", "Gary", "TopNews", "Harry"),
  Freq = c(4,2,5,3)
)

plot_ly(df, 
        y = ~Segments, 
        x = ~Freq, 
        type = "bar", 
        orientation = 'h',
        marker = list(color = df$Freq,
                      showscale=T)
        )

Upvotes: 2

Related Questions