将鼠标悬停在绘图中的一个点上时格式化文本 [英] Format the text when hovering over a point in plotly plot
本文介绍了将鼠标悬停在绘图中的一个点上时格式化文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户将鼠标悬停在此 kmeans 图中的一个点上时,我需要将显示的文本从 iris[,1]
和 iris[,2]
更改为变量例如Sepal.Length
、Sepal.Width
.集群应该保持原样
I need to change the text displayed when the user hovers over a point in this kmeans plot from iris[,1]
and iris[,2]
to the variables selected for example Sepal.Length
, Sepal.Width
. The cluster should stay as it is
library(plotly)
library(shiny)
library(ggplot2)
vars <- setdiff(names(iris), "Species")
ui <- pageWithSidebar(
headerPanel('Iris k-means clustering'),
sidebarPanel(
selectInput('xcol', 'X Variable', vars),
selectInput('ycol', 'Y Variable', vars, selected = vars[[2]]),
numericInput('clusters', 'Cluster count', 3, min = 1, max = 9)
),
mainPanel(
plotlyOutput('plot1')
)
)
#server.r
server <- function(input, output, session) {
output$plot1 <- renderPlotly({
# Combine the selected variables into a new data frame
iris<-iris[, c(input$xcol, input$ycol)]
cls <- kmeans(x = iris, centers = input$clusters)
iris$cluster <- as.character(cls$cluster)
ggplotly(ggplot() +
geom_point(data = iris,
mapping = aes(x = iris[,1],
y = iris[,2],
colour = cluster))+
scale_x_discrete(name =as.character(input$xcol))+
scale_y_discrete(name =as.character(input$ycol))+
theme_light()+
geom_text(mapping = aes_string(x = cls$centers[, input$xcol],
y = cls$centers[, input$ycol],
label = 1:input$clusters),
color = "black", size = 4))
})
}
shinyApp(ui, server)
推荐答案
可以在aes
中使用text
来定义显示的文字,并添加tooltip =text"
到 ggplotly
参数明确表示它应该只使用文本映射进行悬停显示
You can use text
in aes
to define the displayed text, and add tooltip = "text"
to the ggplotly
arguments to explicitely says that it should just use the text mapping for the hoovering display
library(plotly)
library(shiny)
library(ggplot2)
vars <- setdiff(names(iris), "Species")
ui <- pageWithSidebar(
headerPanel('Iris k-means clustering'),
sidebarPanel(
selectInput('xcol', 'X Variable', vars),
selectInput('ycol', 'Y Variable', vars, selected = vars[[2]]),
numericInput('clusters', 'Cluster count', 3, min = 1, max = 9)
),
mainPanel(
plotlyOutput('plot1')
)
)
#server.r
server <- function(input, output, session) {
output$plot1 <- renderPlotly({
# Combine the selected variables into a new data frame
iris<-iris[, c(input$xcol, input$ycol)]
cls <- kmeans(x = iris, centers = input$clusters)
iris$cluster <- as.character(cls$cluster)
ggplotly(ggplot() +
geom_point(data = iris,
mapping = aes(x = iris[,1],
y = iris[,2],
colour = cluster,
text = paste0("x = ",input$xcol,
"\ny = ",input$ycol,
"\ncluster: ",cluster )))+
scale_x_discrete(name =as.character(input$xcol))+
scale_y_discrete(name =as.character(input$ycol))+
theme_light()+
geom_text(mapping = aes_string(x = cls$centers[, input$xcol],
y = cls$centers[, input$ycol],
label = 1:input$clusters),
color = "black", size = 4),tooltip = "text")
})
}
shinyApp(ui, server)
这篇关于将鼠标悬停在绘图中的一个点上时格式化文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文