gpt4 book ai didi

javascript - 通过单击堆叠的条形图打开选项卡

转载 作者:行者123 更新时间:2023-12-03 06:55:38 26 4
gpt4 key购买 nike

我正在使用 R、ggplot 和 plotly 构建一个包含转发的堆叠条形图。如果单击条形图的一部分,我希望打开一个新的浏览器选项卡并显示来自该特定日期的推文以及指定的转发数量。但是,当我单击下面示例中的其中一个栏时,会打开一个不同的链接,这表明 url 没有与这些栏正确连接。我该如何解决这个问题?
我以前从未工作过,甚至从未见过 JavaScript,所以答案很可能就在那里。该 plotly 最终将出现在 Shiny 应用程序中。

library(rtweet)
library(ggplot2)
library(plotly)

# Get tweets
tweets <- get_timeline("BBC", n = 10)

# Create dataframe
data <- data.frame("retweet_count" = tweets$retweet_count,
"week" = c(1,1,1,2,2,3,4,5,5,6),
"url" = tweets$status_url)

# Create ggplot
ggplot(data = data,
aes(x = week,
y = retweet_count,
label = url)) +
geom_bar(stat = 'sum',
fill = "darkblue")

# Convert to plotly
p <- ggplotly(
p,
tooltip = c("y", 'label'))

# Add URL data to plot
p$x$data[[1]]$customdata <- data$url

# JS function to make a tab open when clicking on a specific bar
onRender(
p,
"
function(el,x){
el.on('plotly_click', function(d) {
var websitelink = d.points[0].customdata;
window.open(websitelink);
});
}
")

最佳答案

我没有 Twitter 帐户,所以我更改了您的数据集以使用一些 Wikipedia 文章。
您的问题可以通过重新订购 data.frame 来解决。根据网址。如果您使用来自 1:9 的文章运行以下命令一切都按预期工作。一旦您切换到带有链接的数据集 9:1你会得到错误的链接。 Plotly 似乎在内部重新排序 - 与 here 相同的逻辑.
在您的情况下:data <- data[order(data$url),]应该修复订单。
以下工作正常:

# library(rtweet)
library(ggplot2)
library(plotly)
library(htmlwidgets)

# Get tweets
# tweets <- get_timeline("BBC", n = 10)

# Create dataframe
# data <- data.frame("retweet_count" = tweets$retweet_count,
# "week" = c(1,1,1,2,2,3,4,5,5,6),
# "url" = tweets$status_url)

# Create dataframe
# Works!
data <- data.frame("retweet_count" = 1:9,
"week" = 1:9,
"url" = paste0(c("https://en.wikipedia.org/wiki/166"), 1:9))
# Doesn't work!
# data <- data.frame("retweet_count" = 9:1,
# "week" = 9:1,
# "url" = paste0(c("https://en.wikipedia.org/wiki/166"), 9:1))

# Create ggplot
p <- ggplot(data = data,
aes(x = week,
y = retweet_count,
label = url)) +
geom_bar(stat = 'sum',
fill = "darkblue")

# Convert to plotly
p <- ggplotly(
p,
tooltip = c("y", 'label'))

# Add URL data to plot
p$x$data[[1]]$customdata <- data$url

# JS function to make a tab open when clicking on a specific bar
onRender(
p,
"
function(el,x){
el.on('plotly_click', function(d) {
var websitelink = d.points[0].customdata;
window.open(websitelink);
});
}
")

关于javascript - 通过单击堆叠的条形图打开选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64502622/

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