Jel*_*man 6 javascript r ggplot2 plotly r-plotly
我正在使用 R、ggplot 和 plotly 构建一个包含转推的堆叠条形图。如果单击条形图的一部分,我希望打开一个新的浏览器选项卡,并显示该特定日期的推文以及指定的转推量。但是,当我单击下面示例中的其中一个条时,会打开一个不同的链接,表明 url 未与这些条正确连接。我该如何解决这个问题?
我以前从未工作过,甚至从未见过 JavaScript,所以答案很可能就在那里。该图最终将出现在 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);
});
}
")
Run Code Online (Sandbox Code Playgroud)
我没有 Twitter 帐户,因此我更改了您的数据集以使用一些维基百科文章。
data.frame您的问题可以通过根据 URL重新排序来解决。如果您运行下面的文章,1:9一切都会按预期进行。一旦您切换到带有链接的数据集,9:1您将获得错误的链接。Plotly 似乎在内部重新排序 - 与此处的逻辑相同。
在你的情况下: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);
});
}
")
Run Code Online (Sandbox Code Playgroud)