R Highcharter: изменение типа xAxis с даты на время в категорию - PullRequest
0 голосов
/ 09 января 2020

Я хочу изменить тип оси X с даты / времени на категорию. Например: Первичная диаграмма будет линейной диаграммой по группе, а развернутая диаграмма будет столбчатой ​​диаграммой.

Существует решение, приведенное в Highcharts ( Highcharts, можете ли вы изменить тип диаграммы для детализации? , Диаграмма Highcharts с xAxis 'datetime' - используйте категории при развертывании ), но я не могу перевести его в R.

PFB код.

library("dplyr")
library("purrr")
library("highcharter")

df <- data_frame(
  car_brand = c("Hyundai","Hyundai","Hyundai", "Benz","Benz","Benz", "Tesla","Tesla","Tesla"),
  units_sold = c(10,15,20,11,8,13,6,5,7),
  date = c("2019-01-01", "2019-02-01","2019-03-01","2019-01-01","2019-02-01","2019-03-01","2019-01-01","2019-02-01","2019-03-01")
)

df$units_sold <- as.numeric(df$units_sold)
df$date <- as.Date(df$date)
df$drilldown <- paste(df$car_brand, ",", df$date)
carBrands<- df %>%
  select(date, car_brand)

getCarDetails<- function(brands){

  carList <- list()
  listofdfs <- list() #Create a list in which you intend to save your df's.

  for(i in 1:nrow(brands)){ #Loop through the numbers of ID's instead of the ID's

    #You are going to use games[i] instead of i to get the ID
    BrandCarData <- data_frame(
      car = c("H1","H2","H3","H4","H5"),
      units = c(1,2,3,4,5)
    )
    BrandCarData$units <- as.numeric(BrandCarData$units)
    dsCar <- list_parse2(BrandCarData)
    listofdfs[[i]] <- dsCar
    carList[[i]] <- list (name = brands[[2]][i],
                          type = "column",
                          id = paste(brands[[2]][i], ",", brands[[1]][i]),
                          data = listofdfs[[i]])
  }

  return(carList) #Return the list of dataframes.
}

listCar <- getCarDetails(brands = carBrands)

dfDates <- NULL
dfDates$Date <- datetime_to_timestamp(as.Date(df$date, format = "%Y-%m-%d"))
hc <- hchart(df,"line", hcaes(x=date, y =
                                units_sold, group
                              = car_brand )) %>%
  hc_xAxis(categories = dfDates$Date, title = list(text = "<b>Date</b>"), type = "datetime") %>%
  hc_plotOptions(column = list(dataLabels = list(enabled = FALSE), enableMouseTracking = TRUE))%>%
  hc_tooltip(borderWidth = 1.5,
             pointFormat = paste('<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>')) %>%
  hc_legend(enabled = TRUE) %>%
  hc_title(text = "Brand Units Sold Monthy Trend",
           style = list(fontSize = "12px", fontWeight = "bold")) %>%
  hc_yAxis(title = list(text = "<b>Units <br>(In Thousands)</br></b>"))
hc

hc1 <- hc %>%
  hc_drilldown(allowPointDrilldown = TRUE,
               series = listCar)
hc1

Brand-wise Units Sold Monthly Trend

Units Sold for Each Car Model

Как видно из прилагаемых графиков, x На оси второго графика все еще отображаются метки оси X в формате datetime.

Есть предложения?

Ответы [ 2 ]

0 голосов
/ 16 января 2020

На основе входных данных raf18seb я нашел решение для настройки меток оси X при развертывании. В дополнение к этому, я также поделюсь, как изменить заголовок диаграммы и осей.

В моем предыдущем коде я указывал тип оси X в hc_xAxis, как показано в коде ниже:

hc_xAxis(categories = dfDates$Date, title = list(text = "<b>Date</b>"), type = "datetime") 

Это было основной причиной проблемы. Не следует указывать категорию на первичном уровне, вместо этого укажите тип категории на уровне детализации. Пожалуйста, найдите измененный код ниже:

getCarDetails<- function(brands){
  //This function can also be used to dynamically populate the data for drilldown //chart instead of specifiying it inside a JS code.
  carList <- list()
  listofdfs <- list() 
  for(i in 1:nrow(brands)){ 
    BrandCarData <- data_frame(
      car = c("H1","H2","H3","H4","H5"),
      units = c(1,2,3,4,5)
    )
    BrandCarData$units <- as.numeric(BrandCarData$units)
    dsCar <- list_parse2(BrandCarData)
    listofdfs[[i]] <- dsCar
    carList[[i]] <- list (name = brands[[2]][i],
                          type = "column", //Specify the xAxis category type
                          id = paste(brands[[2]][i], ",", brands[[1]][i]),
                          data = listofdfs[[i]])
  }

  return(carList) #Return the list of dataframes.
}

Теперь, в коде ниже, я также добавил код для изменения названия диаграммы и осей при развертывании и развертывании.

hchart(df,"line", hcaes(x=format(as.Date(date), "%b,%Y"), y =
                                 units_sold, group
                               = car_brand )
) %>%
  hc_drilldown(allowPointDrilldown = TRUE,
               series = listCar)%>%
  hc_chart(events=list(drilldown=JS('function(e) 
                                      {
                                       this.setTitle({text: "Units Distribution Across Cars"});
                                       this.yAxis[0].axisTitle.attr({ text: "Units (in Thousands)"});
                                       this.xAxis[0].axisTitle.attr({ text: "Car Types" });
                                    }'),
                       drillup = JS("function() {this.update({title: {text: 'Brand-wise Units Sold Monthy Trend' }});
                                                 this.xAxis[0].setTitle({ text: 'Date' });
            this.yAxis[0].setTitle({ text: 'Units Sold (in Thousands)' });}")
  ))%>%
  hc_xAxis(title = list(text = "<b>Date</b>")) %>%
  hc_plotOptions(column = list(dataLabels = list(enabled = FALSE), enableMouseTracking = TRUE))%>%
  hc_tooltip(borderWidth = 1.5,
             pointFormat = paste('<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>')) %>%
  hc_legend(enabled = TRUE) %>%
  hc_title(text = "Brand-wise Units Sold Monthy Trend",
           style = list(fontSize = "12px", fontWeight = "bold"))%>%
  hc_yAxis(title = list(text = "<b>Units <br>(In Thousands)</br></b>"))

Надеюсь, любой, кто столкнется с этой проблемой в будущем, найдет это полезным.

0 голосов
/ 09 января 2020

Аналогичный вопрос: Развертка до нескольких серий из разных групп - Highcharter (в R)

Подобные примеры развертки Highcharts в R (Highcharter) также можно найти здесь: { ссылка }

edit: Я скопировал / вставил код из моей ссылки выше и добавил всего одну строку "type: 'column'". Вот рабочий пример перехода от строки к столбцу:

library(highcharter)
library(dplyr)
library(purrr)

df <- tibble(x = c(1, 2, 3, 2, 3, 4, 3, 5, 4), y = c(1, 2, 1, 3, 3, 2, 4, 6, 5), key = c(rep("A", 3), rep("B", 3), rep("C", 3)),
             drilldown = c(rep("a", 3), rep("b", 3), rep("c", 3)))

drill1 <- data.frame(
  x = c(1,2,3),
  y = c(3, 3, 1)
)
drill1 <- list_parse2(drill1)

drill2 <- data.frame(
  x = c(1,2,4),
  y = c(1, 5, 1)
)
drill2 <- list_parse2(drill2)

drill3 <- data.frame(
  x = c(1,2,4),
  y = c(4, 3, 1)
)
drill3 <- list_parse2(drill3)


hchart(df, "line", 
       hcaes(x = x, y = y, group = key),
       color = c("#A63A50", "#37123C", "#DDA77B"),
       drilldown = TRUE) %>% 
  hc_chart(events = list(drilldown = JS("function(e) {
            e.preventDefault()
            var chart = this,
              series = [{
                type: 'column',
                data: [5, 5, 5, 3, 2]
              }, {
              type: 'column',
                data: [3, 3, 7, 3, 3]
              }];

            chart.addSingleSeriesAsDrilldown(e.point, series[0]);
            chart.addSingleSeriesAsDrilldown(e.point, series[1]);
            chart.applyDrilldown();
        }"))) %>% 
  hc_plotOptions(line = list(marker = list(enabled = FALSE), legendIndex = 1)) %>% 
  hc_drilldown(
    allowPointDrilldown = TRUE,
    series = list(
      list(
        id = "a",
        data = drill1
      ),
      list(
        id = "b",
        data = drill2
      ),
      list(
        id = "c",
        data = drill3
      )
    )
  )

edit 2:

Вот код, который позволит вам изменить тип xAxis ' в категорию после развертывания:

hc_chart(events = list(drilldown = JS("function(){
    this.xAxis[0].update({
      categories: ['aaa', 'bbb', 'ccc']
    });
  }"))) %>%

API Reference: https://api.highcharts.com/highcharts/chart.events.drilldown https://api.highcharts.com/class-reference/Highcharts.Axis#update https://api.highcharts.com/highcharts/xAxis.categories

...