在ggplotly散点图中添加自定义数据标签

2024-05-14

我想显示Species对于每个数据点,当光标位于该点上方而不是 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 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")))

 }) 




}

1. 工具提示

您可以通过多种方式更改工具提示,如下所述here https://stackoverflow.com/questions/36325154/how-to-choose-variable-to-display-in-tooltip-when-using-ggplotly。只是为了展示Species在工具提示中,类似这样的内容应该有效:

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"))

2. 持久标签

我不知道如何离开plotly单击后该点上的工具提示,但您可以使用plotly点击事件 https://plot.ly/r/shiny-coupled-events/获取单击的点,然后添加geom_text层到你的ggplot.

3. 最小示例

我已经修改了您的代码以制作一个更简单的示例。一般来说,如果您创建一个最小的例子 https://stackoverflow.com/a/48343110/8099834并删除应用程序中不需要重新创建问题的部分(例如更改字体)。

library(shiny)
library(plotly)
library(ggplot2)

ui <- fluidPage(
  plotlyOutput("iris")
)

server <- function(input, output, session) {
  output$iris <- renderPlotly({
      # set up plot
      p1 <- ggplot(iris, aes_string(x = "Sepal.Length", 
                                    y = "Sepal.Width",
                                    key = "Species")) +
          geom_point()

      # get clicked point
      click_data <- event_data("plotly_click", source = "select")
      # if a point has been clicked, add a label to the plot
      if(!is.null(click_data)) {
          label_data <- data.frame(x = click_data[["x"]],
                                   y = click_data[["y"]],
                                   label = click_data[["key"]],
                                   stringsAsFactors = FALSE)
         p1 <- p1 + 
             geom_text(data = label_data,
                       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)

编辑:保留所有标签

您可以使用以下命令将每次点击存储在反应式 data.frame 中reactiveValues并使用这个 data.frame 为您geom_text layer.

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在ggplotly散点图中添加自定义数据标签 的相关文章

  • 使用 ggplot 绘制函数,相当于 curve()

    是否有使用绘制函数的等效方法ggplot to the curve 基础图形中使用的命令 我想另一种选择是创建一个函数值向量并绘制一条连接线 但我希望有更简单的东西 Thanks 您可以使用以下命令添加曲线stat function ggp
  • 在另一个函数中定义一个函数的优雅方式

    我想构建 f lt function g lt function x x 2 list 这样我就可以使用调用f g 4 并有list 导致list 16 一般来说我会在里面定义几个临时函数f用户在调用时可以调用f 我已经尝试过assign
  • R 中自定义函数的等高线图

    我正在使用一些自定义函数 我需要根据参数的多个值为它们绘制轮廓 这是一个示例函数 我需要画这样的等高线图 任何想法 Thanks 首先你构造一个函数 fourvar它将这四个参数作为参数 在这种情况下 您可以使用 3 个变量来完成此操作 其
  • R 比较所有列对的每个值[重复]

    这个问题在这里已经有答案了 我有一个 18x18 的数据框 我想将所有可能的列对相互比较 以便对于每对两列 18 行中的值相互比较 由于我的数据太大 无法放在这里 我写了一个小例子来说明到目前为止我所想到的 gt a lt c 1 18 g
  • 在 R 的 stargazer 表中设置注释格式

    我在用stargazer包来生成 回归输出 表 一切都在奇迹般地进行 直到我开始编辑笔记 First 换行很难 但是 Bryansuggests https stackoverflow com questions 21720264 star
  • 有条件地将字符串转换为特定数值

    我确信对此有一个简单的答案 但我已经扫描了堆栈溢出 但无法找到解决方案 似乎 sapply 和 ifelse 函数的组合可能可以完成这项工作 但我不确定 所以我有一个包含字符的数据框 除了一列是数值 Create dataframe whi
  • 将从数据透视表包生成的数据透视表转换为数据帧

    我正在尝试制作一个数据透视表pivottabler包裹 我想将数据透视表对象转换为数据框 以便我可以将其转换为数据表 带有 DT 并在 Shiny 应用程序中渲染它 以便可以下载 library pivottabler pt qpvt mt
  • R 中的金字塔图

    对于示例数据集 我按国家 地区创建了一个金字塔图 显示人口中男性和女性超重的水平 library plotrix xy males overweight lt c 23 2 33 5 43 6 33 6 43 5 43 5 43 9 33
  • R data.table:在当前测量之前对出现次数进行计数

    我有一组在几天内进行的测量结果 测量次数通常为 4 任何测量中可以捕获的数字范围为 1 5 在现实生活中 给定测试集 范围可能高达 100 或低至 20 我想每天计算每个值在当天之前发生的次数 让我用一些示例数据来解释 test data
  • 将 XML 的所有字段(和子字段)导入为数据框

    为了进行一些分析 我想使用 R 和 XML 包将 XML 导入数据帧 XML 文件示例
  • R 如何按行值进行分组、拆分或子集

    这是上一个问题的延续R 如何按行值分组 分裂 https stackoverflow com questions 64602607 r how to group by row value split 输入数据帧的变化是 id str c x
  • 使用 R 中“rpart”包中的生存树来预测新的观察结果

    我正在尝试使用 R 中的 rpart 包来构建生存树 并且我希望使用这棵树来对其他观察结果进行预测 我知道有很多涉及 rpart 和预测的问题 但是 我还没有找到任何解决 我认为 特定于将 rpart 与 Surv 对象一起使用的问题的方法
  • 在 R 中,如何让 PRNG 在平台之间给出相同的浮点数?

    在 R 4 1 1 中运行以下代码会在平台之间产生不同的结果 set seed 1 x lt rnorm 3 3 print x 22 0 83562861241004716 intel windows 0 8356286124100471
  • 在 Microsoft Windows 上安装 RQuantLib

    我需要安装R包RQuantLib在 Microsoft Windows 计算机上 这个包没有二进制文件 所以我下载了 tar 源 我打开它 它包含 QuantLib C 库 所以我需要编译这个包 我不想安装 Visual Studio 我使
  • 我们如何获取R中的商品价格?

    正如标题 我知道我们可以使用quantmod包来获取股票价格 但我们如何检索黄金 石油或农产品等商品价格 Use Quandl包 这里有一些例子 Gold lt Quandl LBMA GOLD WTI lt Quandl CHRIS CM
  • 错误:列索引必须最多为 1,如果... heatmap.2

    我在 heatmap 2 中收到错误 我在这里发现了类似的错误R knnImputation 给出错误 https stackoverflow com questions 45117125 r knnimputation giving er
  • R 版本 4.0.0 上的 ROracle

    当尝试使用 ROracle 时 我收到以下错误消息 gt library ROracle Error package or namespace load failed for ROracle package ROracle was inst
  • 如何更改 R Markdown HTML 文档中目录的颜色和属性?

    我花了很多时间谷歌搜索这个 但似乎无法弄清楚 我正在使用 R Markdown 制作 HTML 文档 文档在这里 http rmarkdown rstudio com html document format html http rmark
  • 在r中的数据框中循环线性回归输出

    我有一个下面的数据集 我想在其中对每个国家和州进行线性回归 然后绑定数据集中的预测值 添加另外三列后的最终数据框 我已经对一个国家和一个地区进行了此操作 但想对每个国家和地区进行此操作 并将预测值 上限值和下限值放回到cbind的数据集中
  • 获得各州的边界

    编辑7 经过相当多的帮助后 我已经能够得到一张接近我需要的结果的地图 但我仍然需要在地图上显示州边界 但我无法弄清楚 为了制作一个合适的可重现示例 我需要链接到数据集 因为输出太大 为了使事情变得简单 我只对三个状态进行子集化 但边界线不显

随机推荐