user10781624
user10781624

Reputation: 141

R - arrange bars in grouped hchart

I am trying to create a grouped highcharts barchart where the bars are arranged alphabetically.

The example below shows what I am trying to do:

library(highcharter)

#create dataframe pokemon
pokemon <- pokemon <- structure(list(type_1 = c("poison", "poison", "poison", "poison", 
                                     "rock", "rock", "rock", "rock", "rock", "rock", "rock", "rock", 
                                     "rock", "poison", "rock", "rock", "rock", "rock", "rock", "rock", 
                                     "rock", "rock", "rock", "rock", "rock", "poison", "poison", "poison", 
                                     "poison", "poison", "poison", "rock", "rock", "rock", "rock", 
                                     "rock", "rock", "poison", "poison", "rock", "rock", "rock", "rock", 
                                     "rock")
                          , type_2 = c("ground", "ground", "flying", "flying", "ground", 
                                       "ground", "ground", "ground", "water", "water", "water", "water", 
                                       "flying", "flying", "ground", "ground", "dark", "psychic", "psychic", 
                                       "grass", "grass", "bug", "bug", "steel", "steel", "dark", "dark", 
                                       "bug", "dark", "fighting", "fighting", "steel", "flying", "flying", 
                                       "fighting", "water", "water", "water", "dragon", "dragon", "dragon", 
                                       "ice", "ice", "fairy"))
                     , class = c("tbl_df", "tbl", "data.frame"
                                                         )
                     , row.names = c(NA, -44L))

# create chart
pokemon%>% 
  group_by(type_1, type_2) %>% 
  summarise(n = n())%>%
  arrange(type_2)%>%
  hchart(type = "bar", hcaes(x = type_2, group = type_1, y = n))

But the arrange does not work, the bars are not ordered by type_2.

It does work if I don't use a grouping variable in my hchart:

pokemon%>%
  group_by(#type_1, 
    type_2) %>% 
  summarise(n = n())%>%
  arrange(type_2)%>%
  hchart(type = "bar", hcaes(x = type_2#, group = type_1
                             , y = n))

Is there any way to order my bars while using a grouping variable?

I am using R 3.5.2

Upvotes: 1

Views: 1788

Answers (1)

user10781624
user10781624

Reputation: 141

I think I've already found the solution by using highcharts() and hc_add_series, this does allow for arranging:

pokemon <- pokemon %>% 
  group_by(type_1, type_2) %>% 
  summarise(n = n())%>%
  arrange(type_2)

# create chart
highchart() %>% 
  hc_add_series(pokemon, type = "bar", hcaes(x = type_2, group = type_1, y = n)) %>% 
  hc_xAxis(categories = pokemon$type_2)

Upvotes: 2

Related Questions