gpt4 book ai didi

r - ggplotly 与直方图 - 无法使其工作

转载 作者:行者123 更新时间:2023-12-01 12:50:44 25 4
gpt4 key购买 nike

我正在尝试通过 ggplotly 为带有叠加密度函数的直方图制作动画,使用的代码看起来像

ggplot() +
geom_point(data_1 = aes(..some aesthetic.., frame = step)) +
geom_hist(data_2 = aes(..some other aesthetic.., frame = step))

此代码不起作用,但在我看来,直方图通常不适用于 ggplotly。我想知道你们是否可以提供帮助。

数据

这是一个例子; frame 是定义动画索引的变量

# Some data (points) for the first aes
df_1 = data.frame(x = 1:10, y = 1:10, frame = 1:10)

# Other data (for each frame multiple values from 3 groups)
df_2 = lapply(1:10, function(w)
data.frame(
val = runif(10, min = w, max = w + 1), # Value
code = sample(1:3, 10, replace = TRUE), # Color for fill
frame = w)
)
df_2 = Reduce(rbind, df_2)

积分ggplots 完美呈现,动画 ggplotly(pl) 也是如此。

pl = ggplot() + 
geom_point(data = df_1, aes(x, y, frame = frame))

# OK!
print(pl)
plotly::ggplotly(pl)

直方图

ggplots 完美呈现。

gg_pl = ggplot() +
geom_histogram(data = df_2, aes(
val,
fill = factor(code),
frame = frame)) +
scale_fill_brewer()

# OK
print(gg_pl)

但是通过 ggplotly 渲染崩溃了

# Error!
plotly::ggplotly(gg_pl)

Error in -data$group : invalid argument to unary operator

直方图 + 点

和以前一样,ggplot 有效,但动画无效。

pl = ggplot() + 
geom_point(data = df_1, aes(x, y, frame = frame)) +
geom_histogram(data = df_2,
aes(val, fill = factor(code), frame = frame))

# OK!
print(pl)

# Errors as before
plotly::ggplotly(pl)

最佳答案

这不是您要找的东西,但这是一个开始,也许它会有所帮助。这是使用 plot_ly 的动画直方图。

library(plotly)
p = df_2 %>%
plot_ly(x=~val,
type='histogram',
color=~code,
frame=~frame,
alpha=0.7)
p

我无法让点与直方图一起制作动画,但上面的点是一样的。如果您取消注释 #frame=~frame 行,这些点将动画化,但直方图将消失,除了第一帧和最后一帧。

  p = plot_ly() %>%
add_histogram(data=df_2,
x=~val,
color=~code,
frame=~frame)%>%
add_trace(data=df_1,
x=~x,
y=~y,
frame=~frame,
type='scatter',
mode='markers')
p %>% animation_opts(easing='linear')

关于r - ggplotly 与直方图 - 无法使其工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521311/

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