R 在ggplotly散点图中添加自定义数据标签
我想在光标位于点而不是x和y值上时,为每个数据点显示R 在ggplotly散点图中添加自定义数据标签,r,shiny,plotly,ggplotly,R,Shiny,Plotly,Ggplotly,我想在光标位于点而不是x和y值上时,为每个数据点显示物种。我使用iris数据集。此外,我希望能够点击一个数据点,使标签持久化,并且在我选择绘图中的新点时不会消失。(如有可能)。最基本的是标签。持久性问题是一个加号。这是我的应用程序: ## Note: extrafont is a bit finnicky on Windows, ## so be sure to execute the code in the order ## provided, or else ggplot won't f
物种
。我使用iris
数据集。此外,我希望能够点击一个数据点,使标签持久化,并且在我选择绘图中的新点时不会消失。(如有可能)。最基本的是标签。持久性问题是一个加号。这是我的应用程序:
## Note: extrafont is a bit finnicky on Windows,
## so be sure to execute the code in the order
## provided, or else ggplot won't find the font
# Use this to acquire additional fonts not found in R
install.packages("extrafont");library(extrafont)
# Warning: if not specified in font_import, it will
# take a bit of time to get all fonts
font_import(pattern = "calibri")
loadfonts(device = "win")
#ui.r
library(shiny)
library(ggplot2)
library(plotly)
library(extrafont)
library(ggrepel)
fluidPage(
# App title ----
titlePanel(div("CROSS CORRELATION",style = "color:blue")),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Select a file ----
fileInput("file1", "Input CSV-File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
# Horizontal line ----
tags$hr(),
# Input: Checkbox if file has header ----
checkboxInput("header", "Header", TRUE),
# Input: Select separator ----
radioButtons("sep", "Separator",
choices = c(Comma = ",",
Semicolon = ";",
Tab = "\t"),
selected = ","),
# Horizontal line ----
tags$hr(),
# Input: Select number of rows to display ----
radioButtons("disp", "Display",
choices = c(Head = "head",
All = "all"),
selected = "head")
),
# Main panel for displaying outputs ----
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Table",
shiny::dataTableOutput("contents")),
tabPanel("Correlation Plot",
tags$style(type="text/css", "
#loadmessage {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
padding: 5px 0px 5px 0px;
text-align: center;
font-weight: bold;
font-size: 100%;
color: #000000;
background-color: #CCFF66;
z-index: 105;
}
"),conditionalPanel(condition="$('html').hasClass('shiny-busy')",
tags$div("Loading...",id="loadmessage")
),
fluidRow(
column(3, uiOutput("lx1")),
column(3,uiOutput("lx2"))),
hr(),
fluidRow(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
column(3,uiOutput("td")),
column(3,uiOutput("an"))),
fluidRow(
plotlyOutput("sc"))
))
)))
#server.r
function(input, output) {
output$contents <- shiny::renderDataTable({
iris
})
output$lx1<-renderUI({
selectInput("lx1", label = h4("Select 1st Expression Profile"),
choices = colnames(iris[,1:4]),
selected = "Lex1")
})
output$lx2<-renderUI({
selectInput("lx2", label = h4("Select 2nd Expression Profile"),
choices = colnames(iris[,1:4]),
selected = "Lex2")
})
output$td<-renderUI({
radioButtons("td", label = h4("Trendline"),
choices = list("Add Trendline" = "lm", "Remove Trendline" = ""),
selected = "")
})
output$an<-renderUI({
radioButtons("an", label = h4("Correlation Coefficient"),
choices = list("Add Cor.Coef" = cor(subset(iris, select=c(input$lx1)),subset(iris, select=c(input$lx2))), "Remove Cor.Coef" = ""),
selected = "")
})
output$sc<-renderPlotly({
p1 <- ggplot(iris, aes_string(x = input$lx1, y = input$lx2))+
# Change the point options in geom_point
geom_point(color = "darkblue") +
# Change the title of the plot (can change axis titles
# in this option as well and add subtitle)
labs(title = "Cross Correlation") +
# Change where the tick marks are
scale_x_continuous(breaks = seq(0, 2.5, 30)) +
scale_y_continuous(breaks = seq(0, 2.5, 30)) +
# Change how the text looks for each element
theme(title = element_text(family = "Calibri",
size = 10,
face = "bold"),
axis.title = element_text(family = "Calibri Light",
size = 16,
face = "bold",
color = "darkgrey"),
axis.text = element_text(family = "Calibri",
size = 11))+
theme_bw()+
geom_smooth(method = input$td)+
annotate("text", x = 10, y = 10, label = as.character(input$an))
ggplotly(p1) %>%
layout(hoverlabel = list(bgcolor = "white",
font = list(family = "Calibri",
size = 9,
color = "black")))
})
}
##注意:extrafont在Windows上有点过时,
##因此,请确保按顺序执行代码
##提供,否则ggplot将找不到字体
#使用此选项可获取R中未找到的其他字体
安装程序包(“extrafont”);库(外部字体)
#警告:如果在字体导入中未指定,它将
#花点时间获取所有字体
font\u导入(pattern=“calibri”)
loadfonts(device=“win”)
#用户界面
图书馆(闪亮)
图书馆(GG2)
图书馆(绘本)
库(外部字体)
图书馆(ggrepel)
流动摄影(
#应用程序标题----
标题板(div(“互相关”,style=“color:blue”),
#带有输入和输出定义的侧栏布局----
侧边栏布局(
#输入侧栏面板----
侧栏面板(
#输入:选择一个文件----
文件输入(“文件1”,“输入CSV文件”,
倍数=真,
接受=c(“文本/csv”,
“文本/逗号分隔值,文本/普通”,
“.csv”),
#水平线----
标记$hr(),
#输入:如果文件有头,则选中此复选框----
checkboxInput(“标题”、“标题”为TRUE),
#输入:选择分隔符----
单选按钮(“sep”、“分隔符”,
选项=c(逗号=”,“,
分号=“;”,
Tab=“\t”),
已选择“,”,
#水平线----
标记$hr(),
#输入:选择要显示的行数----
单选按钮(“显示”、“显示”,
选项=c(Head=“Head”,
All=“All”),
选定的“头”)
),
#用于显示输出的主面板----
主面板(
tabsetPanel(type=“tabs”,
选项卡面板(“表”,
闪亮::dataTableOutput(“内容”),
tabPanel(“相关图”,
标记$style(type=“text/css”
#加载消息{
位置:固定;
顶部:0px;
左:0px;
宽度:100%;
填充:5px0px 5px0px;
文本对齐:居中;
字体大小:粗体;
字体大小:100%;
颜色:#000000;
背景色:#CCFF66;
z指数:105;
}
“”,conditionalPanel(condition=“$('html').hasClass('shinny-busy')”,
标记$div(“加载…”,id=“加载消息”)
),
fluidRow(
列(3,uiOutput(“lx1”),
列(3,uiOutput(“lx2”),
hr(),
fluidRow(
标记$style(type=“text/css”,
“.Shining输出错误{可见性:隐藏;}”,
“.Shining输出错误:在{可见性:隐藏;}之前”
),
第(3列,输出(“td”),
列(3,uiOutput(“an”)),
fluidRow(
打印输出(“sc”))
))
)))
#服务器.r
功能(输入、输出){
输出$contents1.工具提示
如前所述,您可以通过多种方式更改工具提示。要仅在工具提示中显示物种
,类似的操作应该可以:
library(ggplot2)
library(plotly)
p1 <- ggplot(iris, aes_string(x = "Sepal.Length",
y = "Sepal.Width",
key = "Species")) +
geom_point()
ggplotly(p1, source = "select", tooltip = c("key"))
编辑:保留所有标签
您可以使用reactiveValues
将每次单击存储在一个reactive data.frame中,并将此data.frame用于geom_文本
层
library(shiny)
library(plotly)
library(ggplot2)
ui <- fluidPage(
plotlyOutput("iris")
)
server <- function(input, output, session) {
# 1. create reactive values
vals <- reactiveValues()
# 2. create df to store clicks
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
# 3. add points upon plot click
observe({
# get clicked point
click_data <- event_data("plotly_click", source = "select")
# get data for current point
label_data <- data.frame(x = click_data[["x"]],
y = click_data[["y"]],
label = click_data[["key"]],
stringsAsFactors = FALSE)
# add current point to df of all clicks
vals$click_all <- merge(vals$click_all,
label_data,
all = TRUE)
})
output$iris <- renderPlotly({
# set up plot
p1 <- ggplot(iris, aes_string(x = "Sepal.Length",
y = "Sepal.Width",
key = "Species")) +
geom_point() +
# 4. add labels for clicked points
geom_text(data = vals$click_all,
aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_x = 0.25)
# return the plot
ggplotly(p1, source = "select", tooltip = c("key"))
})
}
shinyApp(ui, server)
库(闪亮)
图书馆(绘本)
图书馆(GG2)
ui这是一个非常有用的答案。点击后是否可以保持显示的值,并且在选择另一个位置时不会消失?我将编辑我的初始帖子,以清楚地说明我描述它的方式可能会混淆。@firmo23乐意帮助!我已经用一个选项更新了我的答案。让我知道它是否适用于您您您的代码似乎适用于此数据集,但在尝试将其应用于实际数据集时,我遇到了一个奇怪的错误。具体而言,我无法生成geom_smooth。而直到最近我才可以。我谈论的是我的实际数据集,因为我可以使用iris生成。我想知道我是否可以私下与您联系。谢谢创建了一个新的问题,可能有助于解决另一个问题,即当绘图最初有皱纹时,我将点与线连接,当我更新它时,线消失。
library(shiny)
library(plotly)
library(ggplot2)
ui <- fluidPage(
plotlyOutput("iris")
)
server <- function(input, output, session) {
# 1. create reactive values
vals <- reactiveValues()
# 2. create df to store clicks
vals$click_all <- data.frame(x = numeric(),
y = numeric(),
label = character())
# 3. add points upon plot click
observe({
# get clicked point
click_data <- event_data("plotly_click", source = "select")
# get data for current point
label_data <- data.frame(x = click_data[["x"]],
y = click_data[["y"]],
label = click_data[["key"]],
stringsAsFactors = FALSE)
# add current point to df of all clicks
vals$click_all <- merge(vals$click_all,
label_data,
all = TRUE)
})
output$iris <- renderPlotly({
# set up plot
p1 <- ggplot(iris, aes_string(x = "Sepal.Length",
y = "Sepal.Width",
key = "Species")) +
geom_point() +
# 4. add labels for clicked points
geom_text(data = vals$click_all,
aes(x = x, y = y, label = label),
inherit.aes = FALSE, nudge_x = 0.25)
# return the plot
ggplotly(p1, source = "select", tooltip = c("key"))
})
}
shinyApp(ui, server)