gpt4 book ai didi

r - 如何在 highcharter 中生成以 y 为因子的散点图?

转载 作者:行者123 更新时间:2023-12-02 20:30:10 24 4
gpt4 key购买 nike

问题:

我想用 highcharter::hchart 生成散点图,其中yfactor ,x 是 date .

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

有什么解决办法吗?或者是"scatter"只是图表类型错误?

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


示例:

假设我想生成一个按类型列出的出版物时间表。我想要一个带有 d$type 的散点图(=y 轴)和 d$date (=x 轴)和 highcharter工具提示应该显示 d$title , d$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"不接受factory .

我实现此功能的唯一方法是转换 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

最佳答案

另一种选择是:

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 开始。

关于r - 如何在 highcharter 中生成以 y 为因子的散点图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49034106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com