user10781624
user10781624

Reputation: 141

Ordering the stacking in a highcharts bar chart in R

I am trying to make a stacked bar chart, where de values that are being stacked have a specific order.

I understand that you can do this by ordering the series as they come in. But I am adding all series at once, so I'm not sure how this would work.

I have tried ordering the dataframe itself, but this does not appear to do anything. I've also read about indexing, but I haven't been able to get that to work.

An example:

# create data frame
cat1 <- c('cat','dog','cat','bunny','dog','bunny')
cat2 <- c('brown','grey','grey','grey','brown','brown')
value <- c(15,80,85,36,20,64)

# Join the variables to create a data frame
df <- data.frame(cat1,cat2,value)
df

#create barchart
hchart(df, type = 'bar', hcaes( y = value, group=cat2, x = cat1)) %>%
  hc_plotOptions(series = list(stacking = "normal"))

This creates a barchart with grey first and brown second. But I would like to set the order myself. Is this possible?

Off course, I can split my dataframe into separate datasets, but I also have charts where I have many categories that need to be stacked. I would rather not add all of these separately.

Upvotes: 2

Views: 2222

Answers (2)

raf18seb
raf18seb

Reputation: 2146

You can define index property in your series. Here you have JS example of this:

series: [{
    name: 'First',
    data: [5, 6, 4],
    index: 0
  }, {
    name: 'Second',
    data: [1, 3, 2],
    index: 4
  }, {
    name: 'Third',
    data: [6, 7, 2],
    index: 1
  }, {
    name: 'Fourth',
    data: [11, 13, 12],
    index: 3
  }, {
    name: 'Fifth',
    data: [9, 9, 2],
    index: 2
  }]

jsFiddle: https://jsfiddle.net/BlackLabel/uj7qmp3d API: https://api.highcharts.com/highcharts/series.bar.index

Upvotes: 0

Rushabh Patel
Rushabh Patel

Reputation: 2764

You can change levels before plotting -

> df <- within(df, cat2 <- factor(cat2, levels=c("grey","brown")))
> hchart(df, type = 'bar', hcaes( y = value, group=cat2, x = cat1)) %>%
  hc_plotOptions(series = list(stacking = "normal"))

enter image description here

Upvotes: 2

Related Questions