R Highchart // grouped categories in x axis

南楼画角 提交于 2019-12-11 06:09:15

问题


I want to create a stacked bar chart with grouped categories like there.

This is my example dataframe:

region <- c("bavaria", "bavaria", "bavaria", "bavaria", "berlin", "berlin", "berlin", "berlin")
year <- c(2016, 2016, 2017, 2017, 2016, 2016, 2017, 2017)
month <- c(11, 12, 01, 02, 11, 12, 01, 02)
sales <- c(20, 17, 10, 5, 18, 16, 10, 7)
inc_sales <- c(3, 2, 1, 0, 4, 3, 2, 0)
df <- data.frame(region, year, month, sales, inc_sales)

The x axis should be grouped by month / year / region, where month is on top.

I already coded this with only using month as x axis:

library(tidyr)
library(dplyr)
library(highcharter)

highchart() %>% 
      hc_chart(type = "column") %>% 
      hc_title(text = "Sales") %>% 
      hc_xAxis(categories = df$month) %>%
      hc_yAxis(title = list(text = "Sales")) %>% 
      hc_plotOptions(column = list(
        dataLabels = list(enabled = FALSE),
        stacking = "normal",
        enableMouseTracking = TRUE)
      ) %>% 
      hc_series(list(name="sales",data=df$inc_sales),
                list(name="inc_sales",data=df$sales))

Can someone help me to group the categories?


回答1:


You can find the 'Grouped Categories' option helpful: highcharter examples




回答2:


Maybe you can try something like this:

df <- data.frame(region, date=paste(month, year, sep="-"), sales, inc_sales)
df

highchart() %>% 
hc_chart(type = "column") %>% 
hc_title(text = "Some Title") %>%
hc_add_series(name="Sales",data = df$sales  ) %>% 
hc_add_series(name="Inc Sales", data = df$inc_sales) %>%
hc_xAxis(categories = list(
list(
  name =  "Bavaria",
  categories = list("11-2016","12-2016","1-2017","2-2017") 
      ),
list(
  name =  "Berlin",
  categories = list("11-2016","12-2016","1-2017","2-2017") 

)
) )%>%

hc_plotOptions(column = list(stacking = "percent"))


来源:https://stackoverflow.com/questions/40148108/r-highchart-grouped-categories-in-x-axis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!