gos*_*osz 2 r data-visualization highcharts r-highcharter
问题:
我想生成一个散点图highcharter::hchart,其中y是 a factor,x 是 a date。
显然,highcharter::hchart "scatter"不接受因子变量作为 y。
有什么解决方法吗?或者"scatter"只是错误的图表类型?
(评论:我知道ggplotly这是一个不错的选择,但我实际上需要一个highcharter解决方案)
例子:
假设我想按类型生成出版物的时间表。我想要一个带有d$type(=y-axis) 和d$date(=x-axis)的散点图,并且highcharter工具提示应该显示我d$title,d$type和d$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())
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
显然,highcharter::hchart "scatter"不接受factoras 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))
Run Code Online (Sandbox Code Playgroud)
另一种选择是:
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)
Run Code Online (Sandbox Code Playgroud)
请注意as.numeric(type) - 1,这是因为 Javascript 和 highcharts 是 0-index。因此,当我们添加类别名称时,highcharts 将以 0 开头。