如何在highcharter中生成一个因子为y的散点图?

问题描述 投票:2回答:1

问题:

我想用highcharter::hchart产生一个散点图,其中yfactor,x是date

显然,highcharter::hchart "scatter"不接受因子变量为y。

有没有解决方法?或者"scatter"只是错误的图表类型?

(评论:我知道ggplotly将是一个很好的选择,但我实际上需要一个highcharter解决方案)


例:

我们假设我想按类型生成出版物的时间表。我想要一个带有d$type(= y轴)和d$date(= x轴)的散点图,highcharter工具提示应该显示d$titled$typed$date(格式正确)。

library(stringi)
library(tidyverse)
library(highcharter)

### create example data
d <- data.frame(date = sample(seq(as.Date("2001/1/1"),
                                  as.Date("2003/1/1"),
                                  by = "day"),
                              30), # Date of publication
                title = stringi::stri_rand_strings(30, 5), # Title of publication
                type = rep(c("book","article","tweet"),
                           length.out=30)) # Publication type
glimpse(d)
#>Observations: 30
#>Variables: 3
#>$ date  <date> 2001-02-21, 2001-12-31, 2002-09-02, 2002-12-11, 2001-...
#>$ title <fct> NvHuI, 81HoS, TsyWs, KbTT2, I2p4f, ASasv, HuclA, cmihb...
#>$ type  <fct> book, article, tweet, book, article, tweet, book, arti...


### ggplot2: static plot
ggplot(d, aes(x=date,
              y=type)) +
  geom_point(aes(colour=type), 
             alpha=0.5,
             size = 3) + 
  scale_x_date(date_labels = "%m / %Y") +
  theme_light() +
  theme(panel.grid.minor.x = element_blank())

ggplot

ggplot2::geom_points在这里做得很好。

但是,我希望图表是交互式的(工具提示显示标题等等)。所以我将尝试使用highcharter::hchart

### highcharter: interactive plot
# A.) NOT WORKING, because y is a factor
hchart(d,
       "scatter",
       hcaes(x = date,
             y = type,
             group = type))   

显然,highcharter::hchart "scatter"不接受factor作为y

我得到这个工作的唯一方法是将d$type转换为数字......然后xAxisLabels和工具提示是错误的......

# B.) WORKING, because y is numeric
hchart((d %>% 
          mutate(typenum = as.numeric(type))), 
       "scatter",
       hcaes(x = date,
             y = typenum,
             group = typenum))   

hchart

r highcharts data-visualization r-highcharter
1个回答
4
投票

另一种选择是:

lvls <- d %>% pull(type) %>% levels()

d %>% 
  mutate(typenum = as.numeric(type) - 1) %>% 
  hchart("scatter", hcaes(x = date, y = typenum, group = type)) %>% 
  hc_yAxis(categories = lvls)

enter image description here

注意as.numeric(type) - 1,这是因为Javascript然后highcharts是0索引。因此,当我们添加类别名称时,highcharts将从0开始。

© www.soinside.com 2019 - 2024. All rights reserved.