我正在构建一个包含使用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);
});
}
")
我没有twitter帐户,所以我更改了您的数据集以使用一些维基百科文章。
您的问题可以通过根据URL重新排序data.frame
来解决。如果您使用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);
});
}
")