使用下拉菜单在 Rmarkdown 中打印不同的 ggplotly 图

问题描述 投票:0回答:1

我有一系列具有这种格式的数据:

基因农场 s0 上一页 伊瓦尔
fam_VO056_k119_707118_2 -2.94891455 1.897019 纬度_c
fam_VO118_k119_1069373_4 -2.63244195 1.897019 纬度_c
fam_VO015_k119_739705_2 -2.54050825 1.897019 干旱指数_v3
fam_VO203_k119_389361_1 -1.25734198 4.336043 MAT_wc2
fam_VO036_k119_254678_4 -1.15872311 1.897019 MAT_wc2

最多 13 个不同的值

Yvar

我正在尝试绘制 13 个图,每个

Yvar
值一个,x 轴为
GeneFam
,y 轴为
s0
,条形由
Prev
梯度填充:

ple_wts <- ggplot(mydata, aes(x = s0, y = reorder(GeneFam, s0), fill = Prev)) +
  geom_bar(stat = "identity") +
  scale_fill_gradientn(colours = c("skyblue", "dodgerblue3", "brown1", "firebrick4")) +
  facet_wrap(~Yvar, scales = "free")

但我想使用plotly或类似的东西以交互方式绘制它们,因此当从下拉菜单中选择每个

Yvar
方面时,它会单独出现。

我正在 Rmarkdown 中工作,我希望输出是 html。初始 Markdown 参数为:

---
title: "<span style='font-size: 25px'><b>Something</b></span>"
subtitle: "<span style='font-size: 22px'><u>Something 2</u></span>"
author: "Myname"
date: '`r format(Sys.time(), "%d/%m/%Y")`'
output:
  rmdformats::material:
    highlight: kate
    self_contained: yes
    fig_caption: yes
    fig_height: 8
    fig_width: 12
    thumbnails: false
    lightbox: true
---

我怎样才能实现这个目标?

注意它不需要是基于facet的图,如果需要,它也可以是ggplots列表

r ggplot2 plotly r-markdown
1个回答
0
投票

使用

plotly
包的一种解决方案:

library(plotly)

my_colors <- c("skyblue", "dodgerblue3", "brown1", "firebrick4") |> 
  col2rgb() |> 
  t() |> 
  rgb(maxColorValue = 255)


# plot
mydata |> 
  plot_ly(
    x = ~s0, 
    y = ~GeneFam,
    color = ~Prev,
    colors = my_colors,
    type = "bar",
    transforms = list(
      list(
        type = "filter",
        target = ~Yvar,
        operation = "=",
        value = unique(mydata$Yvar)
      )
    )
  ) |> 
  layout(
    updatemenus = list(
      list(
        x = 1.5,
        y = 1.2,
        type = "dropdown",
        active = 0,
        buttons = lapply(unique(mydata$Yvar),
                         function(x) list(method = "restyle",
                                          args = list("transforms[0].value", x),
                                          label = x)
        )
      )
    )
  )

数据

mydata <- read.table(text="GeneFam  s0  Prev    Yvar
fam_VO056_k119_707118_2 -2.94891455 1.897019    Latitude_c
fam_VO118_k119_1069373_4    -2.63244195 1.897019    Latitude_c
fam_VO015_k119_739705_2 -2.54050825 1.897019    Aridity_Index_v3
fam_VO203_k119_389361_1 -1.25734198 4.336043    MAT_wc2
fam_VO036_k119_254678_4 -1.15872311 1.897019    MAT_wc2", header=TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.