English 中文(简体)
如何用Plotly Button改变地块?
原标题:How to change plots with Plotly button?

I am trying to create an interactive graph where you can toggle between 4 different bar charts. I have this code that successfully makes 1 bar chart with a button with 4 options, however it is only showing parts of the first plot on each toggle page, not the different plots. Any ideas on how to fix this?

barp <- ggplot(data = dat, aes(x = AnnualIncome_Label, fill = interest_Label)) +
  geom_bar(position = "fill") +
  xlab("Annual Income") +
  ylab("Proportion") +
  ggtitle("Proportional Interest in Clinical Trials by Income") +
  labs(fill = "Clinical Trial Interest Level") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_fill_manual(values = c("khaki2", "lemonchiffon1", "#DADAEB", "#9E9AC8", "#6A51A3"))

# Stacked bar chart for "Education" and "Interest_Label"
plot2 <- ggplot(data = dat, aes(x = Ed_Label, fill = interest_Label)) +
  geom_bar(position = "fill") +
  xlab("Education Level") +
  ylab("Proportion") +
  ggtitle("Proportional Interest in Clinical Trials by Education Level") +
  labs(fill = "Clinical Trial Interest Level") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_fill_manual(values = c("khaki2", "lemonchiffon1", "#DADAEB", "#9E9AC8", "#6A51A3"))

# Stacked bar chart for "EnglishProf_Label" and "Interest_Label"
plot3 <- ggplot(data = dat, aes(x = EnglishProf_Label, fill = interest_Label)) +
  geom_bar(position = "fill") +
  xlab("English Proficiency Label") +
  ylab("Proportion") +
  ggtitle("Proportional Interest in Clinical Trials by English Proficiency") +
  labs(fill = "Clinical Trial Interest Level") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_fill_manual(values = c("khaki2", "lemonchiffon1", "#DADAEB", "#9E9AC8", "#6A51A3"))

# Stacked bar chart for "HelpMedLit_Label" and "Interest_Label"
plot4 <- ggplot(data = dat, aes(x = HelpMedLit_Label, fill = interest_Label)) +
  geom_bar(position = "fill") +
  xlab("Help with Medical Literacy Label") +
  ylab("Proportion") +
  ggtitle("Proportional Interest in Clinical Trials by Help Understanding Medical Literature") +
  labs(fill = "Clinical Trial Interest Level") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1), 
    legend.position = "none") +
  guides(fill = FALSE) +
  scale_fill_manual(values = c("khaki2", "lemonchiffon1", "#DADAEB", "#9E9AC8", "#6A51A3"))

plotly_plot1 <- ggplotly(plot1)
plotly_plot2 <- ggplotly(plot2)
plotly_plot3 <- ggplotly(plot3)
plotly_plot4 <- ggplotly(plot4)


plotly_plots <- list(plotly_plot1, plotly_plot2, plotly_plot3, plotly_plot4)


# Create buttons for dropdown menu
buttons <- list(
  list(method = "restyle",
       args = list("visible", list(TRUE, FALSE, FALSE, FALSE)),
       label = "Plot 1"),
  list(method = "restyle",
       args = list("visible", list(FALSE, TRUE, FALSE, FALSE)),
       label = "Plot 2"),
  list(method = "restyle",
       args = list("visible", list(FALSE, FALSE, TRUE, FALSE)),
       label = "Plot 3"),
  list(method = "restyle",
       args = list("visible", list(FALSE, FALSE, FALSE, TRUE)),
       label = "Plot 4")
)
initial_fig <- plotly_plots[[1]]

initial_fig <- initial_fig %>%layout(
  title = "Dropdown Menu - Plot Selection",
  updatemenus = list(
    list(
      buttons = buttons
    )
  )
)
initial_fig

我希望 but子或 drop平的菜菜单在地块——“开发”和地块(开发1,块地——2,块地——开发3,块地——开发4)之间改变。

现在是,它看着它刚刚四分五裂地——1号——四号。

问题回答

When you use buttons, restyle only affects the trace, not the layout. Additionally, visibility is per trace, generally this equates to per color in a discretely colored plot.

BTW:它希望你们重新加入SO;欢迎社区! 如果你想很快得到大量答案,那么最好能够使你的问题重新提出。 其中包括<代码>dput(或reprex:reprex(>)的样本数据。 查阅: R reproducible questions

如果这种方法符合你们的期望。

由于你的问题无法再提,我使用了R数据基代码<>mtcars。 我用<代码>ggplot2将两个任意的条块同起来。

library(tidyverse)
library(plotly)
library(htmltools)

# prep data
mtc <- mtcars %>% mutate(cyl = as.factor(cyl), across(vs:carb, as.factor))

# plots used to demo
(p1 <- ggplot(mtc, aes(cyl, fill = gear)) + geom_bar(position = "fill"))
(p2 <- ggplot(mtc, aes(cyl, fill = carb)) + geom_bar(position = "fill"))

下一个轨道结合功能htmltools:browsable, a Javascript function to sets on each other, a Javascript function to interpret thedown menu, thedown menu, and the twogets.

当见tags$option(数值=“B”、“B”)时,这正在确定你在下降的菜单中看到的名字。 www.un.org/chinese/ga/president (以下最后一行代码:ggplotly(p1)。) 每一<代码>option 必须有独一无二的<代码> 。

参看该法典最后三行中的这些标签和阴谋。 例如,在您的问询中,你把第1级的“第1级”贴上标签,在使用该代码的倒数中使用这一标签,你将修改<代码>的标签(价值=“A”,选定=NA,“A”至tags$option(价值=“A”,选定=NA,“Plot 1”)

如果你有4块地块,则需要4个“密码>标值/代码”,注明价值和标签。 只有第一个<代码>option将包括s selected = NA

browsable(
  tagList(
    tags$head(
      tags$script(HTML(
        "setTimeout(function(){                         /* stack plots */
            $( [id^="htmlwidget-"] ).css({top:  20vh ,  /* add button space */
                                            position: absolute ,
                                             z-index : -10});
            $( [id^="htmlwidget-"] ).first().css({ z-index : 1000});
          }, 100)")),
      tags$script(HTML(
        "function getOps(sel) {                         /* activate dropdown */
            graphy = document.querySelectorAll( [id^="htmlwidget-"] );
            $( [id^="htmlwidget-"] ).css({ z-index : -10});
            for(i = 0; i < sel.length; i++) {
              opt = sel.options[i];
              if ( opt.selected ) {
                console.log(opt);
                graphy[i].style.zIndex =  1000 ;
              } else {
                graphy[1].style.zIndex =  -10 ;
              }
            }
          }"))),
    div(div(tags$label(id = "sb-lab", "for" = "sb", "Plots:"),  # dropdown menu
            tags$select(class = "dropdown form-control", id = "sb", 
                        onchange = "getOps(this)",              # call the JS function
                        tags$option(value = "A", selected = NA, "A",),
                        tags$option(value = "B", "B"))),
        div(ggplotly(p1), ggplotly(p2)))
  ))

“在座的影像描述”/</a

如果你能够想象,你可以定制。 然而,我并不确切地知道你重新寻找的东西,让我在评论中知道。





相关问题
How to plot fitted model over observed time series

This is a really really simple question to which I seem to be entirely unable to get a solution. I would like to do a scatter plot of an observed time series in R, and over this I want to plot the ...

REvolution for R

since the latest Ubuntu release (karmic koala), I noticed that the internal R package advertises on start-up the REvolution package. It seems to be a library collection for high-performance matrix ...

R - capturing elements of R output into text files

I am trying to run an analysis by invoking R through the command line as follows: R --no-save < SampleProgram.R > SampleProgram.opt For example, consider the simple R program below: mydata =...

R statistical package: wrapping GOFrame objects

I m trying to generate GOFrame objects to generate a gene ontology mapping in R for unsupported organisms (see http://www.bioconductor.org/packages/release/bioc/vignettes/GOstats/inst/doc/...

Changing the order of dodged bars in ggplot2 barplot

I have a dataframe df.all and I m plotting it in a bar plot with ggplot2 using the code below. I d like to make it so that the order of the dodged bars is flipped. That is, so that the bars labeled "...

Strange error when using sparse matrices and glmnet

I m getting a weird error when training a glmnet regression. invalid class "dgCMatrix" object: length(Dimnames[[2]]) must match Dim[2] It only happens occasionally, and perhaps only under larger ...

Generating non-duplicate combination pairs in R

Sorry for the non-descriptive title but I don t know whether there s a word for what I m trying to achieve. Let s assume that I have a list of names of different classes like c( 1 , 2 , 3 , 4 ) ...

Per panel smoothing in ggplot2

I m plotting a group of curves, using facet in ggplot2. I d like to have a smoother applied to plots where there are enough points to smooth, but not on plots with very few points. In particular I d ...

热门标签