【问题标题】:Make a boxplot in highchart with a date object in the x axis在 x 轴上使用日期对象在 highchart 中制作箱线图
【发布时间】:2019-09-03 18:12:30
【问题描述】:

我正在尝试在 highchart 中制作一个箱线图,以将其包含在一个闪亮的应用程序中,以及我已经拥有的另一个图表。

问题在于,据我所知,箱线图的行为与其他图不同,当您将日期映射到 x 轴时,它被视为字符串,这意味着:图显示整个日期ex: "2018-04-01" 不是Apr'18 就像它在其他情节中所做的那样。

在这里,我对我所做的事情进行了一点说明

# Packages
library(tidyverse)
library(lubridate)
library(highcharter)
library(magrittr)
library(plotly)

# Data
stocks <- data.frame(
  time = rep(as.Date('2009-01-01') + month(1:12), times = 10),
  stock_price = rnorm(120, 0, 1)
) 
# line plot
stocks %>%
  group_by(time) %>%
  summarise(mean_price = mean(stock_price)) %>%
  hchart(.,  
         type = "line", 
         hcaes(x = "time", 
               y = "mean_price"))
# Box plot first try
# hchart boxplot
stocks %$% 
  hcboxplot(x = stock_price, time) %>%
  hc_chart(type = "column")

在第一次尝试后,我尝试创建一个缩写日期并将其映射到 x 轴,如下所示,但这些框按字母顺序而不是时间顺序显示

# hchart boxplot
stocks %>%
  mutate(month = month(time, label = T),
         year = str_extract(as.character(year(time)), "..$"),
         time2 = paste(month, year, sep = "'")) %$%
  hcboxplot(x = stock_price, time2) %>%         
  hc_chart(type = "column")

我想要的输出是带有 x 轴的图,例如线图或 plotly 的输出

stocks %>%
  group_by(time) %>%
  plot_ly(x = ~time, y = ~stock_price, type = "box") 

【问题讨论】:

    标签: r highcharts boxplot axis-labels


    【解决方案1】:

    arrange()fct_inorder()的帮助下,我相信我已经达到了你想要的结果:

    stocks %>%
      arrange(time) %>%
      mutate(
        month = month(time, label = T),
        year  = str_extract(as.character(year(time)), "..$"),
        time2 = fct_inorder(paste(month, year, sep = "'"))
      ) %$%
      hcboxplot(x = stock_price, time2) %>%
      hc_chart(type = "column")
    

    【讨论】:

    • 这行得通,谢谢。如果轴将对象time 处理为日期(如折线图示例中),无论如何都会很好,因为当我绘制超过两年时,轴标签不太适合。
    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2017-10-28
    相关资源
    最近更新 更多