我想在繪圖上的任何時間和任何位置顯示 x 軸和 y 軸游標坐標。
這就是我要找的:

這是我嘗試過的,但沒有成功:
library(magrittr)
library(ggplot2)
library(plotly)
X <- data.frame(xcoord = -5:5, ycoord = -5:5)
gg <- ggplot(X, aes(xcoord, ycoord)) geom_point() labs(x = "", y = "")
ggplotly(gg) %>%
add_trace(type = "bar",
x = ~xcoord, y = 0,
hoverinfo = 'text',
text = ~paste("X:", xcoord),
yaxis = "y", opacity = 0,
showlegend = FALSE,
marker = list(color = "#ffffff")) %>%
layout(hovermode = "x")
編輯
我無法訪問閃亮的服務器。
uj5u.com熱心網友回復:
我上面鏈接的代碼的主要思想與閃亮無關。請檢查以下內容:
library(plotly)
library(htmlwidgets)
DF <- data.frame(x = 1:10, y = 1:10)
JS <- "
function(el, x){
var id = el.getAttribute('id');
var gd = document.getElementById(id);
var d3 = Plotly.d3;
Plotly.update(id).then(attach);
function attach() {
gd.addEventListener('mousemove', function(evt) {
var xaxis = gd._fullLayout.xaxis;
var yaxis = gd._fullLayout.yaxis;
var bb = evt.target.getBoundingClientRect();
var x = xaxis.p2d(evt.clientX - bb.left);
var y = yaxis.p2d(evt.clientY - bb.top);
Plotly.relayout(gd, 'xaxis.title', 'x: ' parseFloat(x).toFixed(2));
Plotly.relayout(gd, 'yaxis.title', 'y: ' parseFloat(y).toFixed(2));
// Plotly.relayout(gd, 'title', ['x: ' x, 'y : ' y].join('<br>'));
});
};
}"
plot_ly(
DF,
x = ~ x,
y = ~ y,
type = "scatter",
mode = "markers"
) %>% layout(
title = "My Plot",
xaxis = list(title = 'x:'),
yaxis = list(title = 'y:')
) %>% onRender(JS)

使用ggplotly:
gg <- ggplot(DF, aes(x, y)) geom_point() labs(title = "My Plot", x = "x:", y = "y:")
ggplotly(gg) %>% onRender(JS)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/432027.html
