kandi background
Explore Kits

plotly | An interactive graphing library for R | Data Visualization library

 by   ropensci R Version: v4.9.4.1 License: Non-SPDX

 by   ropensci R Version: v4.9.4.1 License: Non-SPDX

Download this library from

kandi X-RAY | plotly Summary

plotly is a R library typically used in Analytics, Data Visualization, WebGL applications. plotly has no bugs, it has no vulnerabilities and it has medium support. However plotly has a Non-SPDX License. You can download it from GitHub.
The plot_ly() function provides a more direct interface to plotly.js so you can leverage more specialized chart types (e.g., parallel coordinates or maps) or even some visualization that the ggplot2 API won’t ever support (e.g., surface, mesh, trisurf, etc).
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • plotly has a medium active ecosystem.
  • It has 2004 star(s) with 585 fork(s). There are 122 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 425 open issues and 1105 have been closed. On average issues are closed in 94 days. There are 31 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of plotly is v4.9.4.1
plotly Support
Best in #Data Visualization
Average in #Data Visualization
plotly Support
Best in #Data Visualization
Average in #Data Visualization

quality kandi Quality

  • plotly has 0 bugs and 0 code smells.
plotly Quality
Best in #Data Visualization
Average in #Data Visualization
plotly Quality
Best in #Data Visualization
Average in #Data Visualization

securitySecurity

  • plotly has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • plotly code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
plotly Security
Best in #Data Visualization
Average in #Data Visualization
plotly Security
Best in #Data Visualization
Average in #Data Visualization

license License

  • plotly has a Non-SPDX License.
  • Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.
plotly License
Best in #Data Visualization
Average in #Data Visualization
plotly License
Best in #Data Visualization
Average in #Data Visualization

buildReuse

  • plotly releases are available to install and integrate.
  • Installation instructions, examples and code snippets are available.
plotly Reuse
Best in #Data Visualization
Average in #Data Visualization
plotly Reuse
Best in #Data Visualization
Average in #Data Visualization
Top functions reviewed by kandi - BETA

kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here

Get all kandi verified functions for this library.

Get all kandi verified functions for this library.

plotly Key Features

An interactive graphing library for R

Installation

copy iconCopydownload iconDownload
install.packages("plotly")

Web-based ggplot2 graphics

copy iconCopydownload iconDownload
library(plotly)
g <- ggplot(faithful, aes(x = eruptions, y = waiting)) +
  stat_density_2d(aes(fill = ..level..), geom = "polygon") + 
  xlim(1, 6) + ylim(40, 100)
ggplotly(g)

Using plotly without ggplot2

copy iconCopydownload iconDownload
plot_ly(z = ~volcano, type = "surface")

Dash ImportError: cannot import name 'get_current_traceback' from 'werkzeug.debug.tbtools'

copy iconCopydownload iconDownload
pip uninstall werkzeug
pip install -v https://github.com/pallets/werkzeug/archive/refs/tags/2.0.1.tar.gz
pip uninstall werkzeug
pip install -v https://github.com/pallets/werkzeug/archive/refs/tags/2.0.1.tar.gz
pip install -U dash
pip install werkzeug==2.0.3
pip install -U dash
pip install werkzeug==2.0.3

R plotly separate functional legends

copy iconCopydownload iconDownload
plot_ly(data = X, x = ~xcoord, y = ~ycoord, 
        split = ~age,
        legendgroup = 'age', # create first split and name it
        legendgrouptitle = list(text = "Age"),
        type = "scatter", mode = "markers",
        color = ~score,
        marker = list(colorbar = list(len = .5, y = .3))) %>% 
  add_trace(split = ~gender,
            legendgroup = 'gender', # create second split and name it
            color = ~score,
            legendgrouptitle = list(text = "Gender")) %>% 
    colorbar(title = 'Score')
library(tidyverse)
library(plotly)
plot_ly() %>%
  add_markers(data = X,
            x = ~xcoord, 
            y = ~ycoord, 
            type = "scatter", 
            mode = "markers",
            #name = "M",
            color = I("grey"),
            split = ~gender,
            legendgroup = 'gender', 
            legendgrouptitle = list(text = "Gender")) %>%
  add_markers(data = X,
              x = ~xcoord, 
              y = ~ycoord, 
              type = "scatter", 
              mode = "markers",
              #name = "M",
              color = I("grey"),
              split = ~age,
              legendgroup = 'age', 
              legendgrouptitle = list(text = "Age")) %>%
  add_trace(data = X,
            x = ~xcoord, 
            y = ~ycoord, 
            type = "scatter", 
            mode = "markers",
            name = "",
            marker = list(color = ~score,
                          colorbar = list(len = .5, y = .3)))
library(crosstalk)

#SharedData object used for filters and plot
shared <- SharedData$new(X) 

crosstalk::bscols(
  widths = c(2, 10),
   list(
     crosstalk::filter_checkbox("Age", 
                                label = "Age",
                                sharedData = shared, 
                                group = ~age),
     crosstalk::filter_checkbox("Gender", 
                                label = "Gender",
                                sharedData = shared, 
                                group = ~gender)
   ),
   plot_ly(data = shared, x = ~xcoord, y = ~ycoord,
           type = "scatter", mode = "markers",
           marker = list(color = ~score,
                         colorbar = list(len = .5, y = .3),
                         cmin = 0, cmax = 6)) %>%
    layout(
      xaxis = list(range=c(.5,6.5)),
      yaxis = list(range=c(.5,6.5))
    )
   )
out <- crosstalk::bscols(...) #previous output object

library(htmltools)
out_tags <- htmltools::renderTags(out)

#check all Age and Gender checkboxes
out_tags$html <- stringr::str_replace_all(
  out_tags$html, 
  '(<input type="checkbox" name="(Age|Gender)" value=".*")/>',
  '\\1 checked="checked"/>'
)
out_tags$html <- HTML(out_tags$html)
# view in RStudio Viewer
browsable(as.tags(out_tags))
#or from Rmd chunk
as.tags(out_tags)
library(crosstalk)

#SharedData object used for filters and plot
shared <- SharedData$new(X) 

crosstalk::bscols(
  widths = c(2, 10),
   list(
     crosstalk::filter_checkbox("Age", 
                                label = "Age",
                                sharedData = shared, 
                                group = ~age),
     crosstalk::filter_checkbox("Gender", 
                                label = "Gender",
                                sharedData = shared, 
                                group = ~gender)
   ),
   plot_ly(data = shared, x = ~xcoord, y = ~ycoord,
           type = "scatter", mode = "markers",
           marker = list(color = ~score,
                         colorbar = list(len = .5, y = .3),
                         cmin = 0, cmax = 6)) %>%
    layout(
      xaxis = list(range=c(.5,6.5)),
      yaxis = list(range=c(.5,6.5))
    )
   )
out <- crosstalk::bscols(...) #previous output object

library(htmltools)
out_tags <- htmltools::renderTags(out)

#check all Age and Gender checkboxes
out_tags$html <- stringr::str_replace_all(
  out_tags$html, 
  '(<input type="checkbox" name="(Age|Gender)" value=".*")/>',
  '\\1 checked="checked"/>'
)
out_tags$html <- HTML(out_tags$html)
# view in RStudio Viewer
browsable(as.tags(out_tags))
#or from Rmd chunk
as.tags(out_tags)

User inputs for R ggplot or plotly without shiny

copy iconCopydownload iconDownload
---
title: "Untitled"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
library(ggplot2)
library(plotly)
library(shiny)
```

```{r shinyInputs}

shiny::numericInput('someInput', "Some Number", value = 5)
shiny::numericInput('someInput2', "Some Number2", value = 2)

plotlyOutput('gg')

```

```{r fig.height=4, fig.width=4}
X <- data.frame(x = 1:10, y = 1:10)

output$gg <- renderPlotly({
  temp <- tibble::tibble(x = input$someInput, y = input$someInput2)
  ggplotly(ggplot(X, aes(x, y)) + geom_point() + geom_point(data = temp, aes(x =         
x, y = y), color = 'red'))
  })
```
---
output: html_document
---

<!-- This is a container for your inputs -->

:::{.input-container}

:::{.xs}
### X coordinate
<input type='number' value=5 id='x1' class='x'>
<input type='number' value=2.5 id='x2' class='x'>
<input type='number' value=7.5 id='x3' class='x'>
:::

:::{.ys}
### Y coordinate
<input type='number' value=10 id='y1'>
<input type='number' value=5 id='y2'>
<input type='number' value=2.5 id='y3'>
:::

:::

<!-- 
I did it using a submit button, I have to read more to make it totally reactive
-->
<input type='button' id='plot' value='Update points' class='btn btn-primary'>


<!-- The next div is a placeholder for the plot -->
<div id="tester" style="width:600px;height:250px;"></div>

<!-- You have to include the plolty.js script -->
<script src="https://cdn.plot.ly/plotly-2.9.0.min.js"></script>


<!-- css configuration to arrange the inputs -->
```{css, echo = FALSE}
input {
  display: block;
}

.xs, .ys {
  display: inline-block;
}
```

<!-- This is the magic, the Js code -->
<!-- language: lang-js -->
```{js, echo=FALSE}

// Get the html element that should contain the plot
plot = document.getElementById('tester');

// Create an object with the default data
let var1 = {
  x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  mode: 'markers',
  type: 'scatter',
  name: 'deafault'
}


let layout = {
  xaxis: {
    range: [ 0, 10.5 ]
  },
  yaxis: {
    range: [0, 10.5]
  },
  title:'Testing'
};

let data = [var1]

// Default plot
Plotly.newPlot(plot, data, layout);


// Using jQuery add an event listener on click to de button
// that way when the user click on it the plot will be updated
$('#plot').click(function(){
  let userInputs = {
    x: [$('#x1').val(), $('#x2').val(), $('#x3').val()],
    y: [$('#y1').val(), $('#y2').val(), $('#y3').val()],
    mode: 'markers',
    type: 'scatter',
    name: 'user'
  }
  
  data = [var1, userInputs] 
  
  Plotly.newPlot(plot, data, layout);
})
``` 
---
title: "ggplotly user inputs"
output: html_document
---
    
:::{#inputcontainerid .input-container}

:::{.xs}
### X coordinate
<input type='number' value=5 id='x1' class='x'>
<input type='number' value=2.5 id='x2' class='x'>
<input type='number' value=7.5 id='x3' class='x'>
:::

:::{.ys}
### Y coordinate
<input type='number' value=10 id='y1'>
<input type='number' value=5 id='y2'>
<input type='number' value=2.5 id='y3'>
:::

:::

<!-- css configuration to arrange the inputs -->
```{css, echo = FALSE}
input {
  display: block;
}

.xs, .ys {
  display: inline-block;
}
```

```{r setup, include=FALSE}
library(ggplot2)
library(plotly)
library(htmlwidgets)
```

```{r out.width='100%', echo=FALSE}
X <- data.frame(x = 1:10, y = 1:10)

JS <- "
function(el, x){
  var id = el.getAttribute('id');
  var gd = document.getElementById(id);
  
  let defaultInputs = {
    x: [$('#x1').val(), $('#x2').val(), $('#x3').val()],
    y: [$('#y1').val(), $('#y2').val(), $('#y3').val()],
    mode: 'markers',
    type: 'scatter',
    name: 'user'
  };
  
  Plotly.addTraces(gd, defaultInputs);
  
  document.getElementById('inputcontainerid').addEventListener('input', function(event){
    let userInputs = {
      x: [[$('#x1').val(), $('#x2').val(), $('#x3').val()]],
      y: [[$('#y1').val(), $('#y2').val(), $('#y3').val()]]
    };
    Plotly.restyle(gd, userInputs, 1);
  });
}
"

gg <- ggplot(X, aes(x, y)) + geom_point()
ggplotly(gg) %>% 
  layout(xaxis = list(autorange = TRUE), yaxis = list(autorange = TRUE)) %>%
  onRender(jsCode = JS)
```

Adding Contour Lines to 3D Plots

copy iconCopydownload iconDownload
plot_ly(x = input_1, y = input_2, z = z,
        contours = list(
          z = list(show = TRUE, start = round(min(z),-2),
                                end = round(max(z),-2), 
                                size = 100))) %>% 
        add_surface()
plot_ly(x = input_1, y = input_2, z = z,
        colors = 'Oranges',
        contours = list(
          z = list(show = TRUE))) %>% 
  add_surface()
plot_ly(x = input_1, y = input_2, z = z,
        contours = list(
          z = list(show = TRUE, start = round(min(z),-2),
                                end = round(max(z),-2), 
                                size = 100))) %>% 
        add_surface()
plot_ly(x = input_1, y = input_2, z = z,
        colors = 'Oranges',
        contours = list(
          z = list(show = TRUE))) %>% 
  add_surface()
fig <- plot_ly(z = ~z) %>% add_surface(
  contours = list(
    z = list(
      show = TRUE,
      # project=list(z=TRUE)       # (don't) project contour lines to underlying plane
      # usecolormap = TRUE,        # (don't) use surface color scale for contours
      color = "white",             # set contour color
      width = 1,                   # set contour thickness
      highlightcolor = "#ff0000",  # highlight contour on hover
      start = 0,                   # include contours from z = 0...
      end = 1400,                  # to z = 1400...
      size = 100                   # every 100 units

    )
  )
)
fig <- plot_ly(z = ~z) %>% add_surface(
  colorscale = "Picnic",
  contours = list(
    x = list(show=TRUE, color="#a090b0", width=2, start=0, end=30, size=7.5),
    y = list(show=TRUE, color="#a090b0", width=2, start=0, end=30, size=7.5),
    z = list(show=TRUE, color="#a090b0", width=2, start=0, end=1400, size=300)
  )
)
fig <- plot_ly(z = ~z) %>% add_surface(
  contours = list(
    z = list(
      show = TRUE,
      # project=list(z=TRUE)       # (don't) project contour lines to underlying plane
      # usecolormap = TRUE,        # (don't) use surface color scale for contours
      color = "white",             # set contour color
      width = 1,                   # set contour thickness
      highlightcolor = "#ff0000",  # highlight contour on hover
      start = 0,                   # include contours from z = 0...
      end = 1400,                  # to z = 1400...
      size = 100                   # every 100 units

    )
  )
)
fig <- plot_ly(z = ~z) %>% add_surface(
  colorscale = "Picnic",
  contours = list(
    x = list(show=TRUE, color="#a090b0", width=2, start=0, end=30, size=7.5),
    y = list(show=TRUE, color="#a090b0", width=2, start=0, end=30, size=7.5),
    z = list(show=TRUE, color="#a090b0", width=2, start=0, end=1400, size=300)
  )
)

TypeError: load() missing 1 required positional argument: 'Loader' in Google Colab

copy iconCopydownload iconDownload
!pip install pyyaml==5.4.1

ggplot geom_tile is distorted in ggplotly

copy iconCopydownload iconDownload
geom2trace.GeomTile <- function(data, params, p) {
  x <- sort(unique(data[["x"]]))
  y <- sort(unique(data[["y"]]))
  # make sure we're dealing with a complete grid
  g <- expand.grid(x = x, y = y)
  g$order <- seq_len(nrow(g))
  g <- merge(g, data, by = c("x", "y"), all.x = TRUE)
  g <- g[order(g$order), ]
...
ggplot(g, aes(x = x, y = y, fill = value)) + geom_tile()
set.seed(1)
X1 <- data.frame(xcoord = c(sample(1:10, n, replace = TRUE), 1:10),
                ycoord = c(sample(1:10, n, replace = TRUE), 1:10),
                value = c(runif(n), rep(NA, 10)))
gg1 <- ggplot(X1) + geom_tile(aes(x = xcoord, y = ycoord, fill = value))
ggplotly(gg1)
# X: original dataframe as defined in the question
X2 <- tidyr::expand_grid(
  xcoord = seq(min(X$xcoord), max(X$xcoord)), 
  ycoord = seq(min(X$ycoord),max(X$ycoord))
  ) %>%    
  dplyr::left_join(X, by=c('xcoord','ycoord'))
gg2 <- ggplot(X2) + geom_tile(aes(x = xcoord, y = ycoord, fill = value))
ggplotly(gg2)
geom2trace.GeomTile <- function(data, params, p) {
  x <- sort(unique(data[["x"]]))
  y <- sort(unique(data[["y"]]))
  # make sure we're dealing with a complete grid
  g <- expand.grid(x = x, y = y)
  g$order <- seq_len(nrow(g))
  g <- merge(g, data, by = c("x", "y"), all.x = TRUE)
  g <- g[order(g$order), ]
...
ggplot(g, aes(x = x, y = y, fill = value)) + geom_tile()
set.seed(1)
X1 <- data.frame(xcoord = c(sample(1:10, n, replace = TRUE), 1:10),
                ycoord = c(sample(1:10, n, replace = TRUE), 1:10),
                value = c(runif(n), rep(NA, 10)))
gg1 <- ggplot(X1) + geom_tile(aes(x = xcoord, y = ycoord, fill = value))
ggplotly(gg1)
# X: original dataframe as defined in the question
X2 <- tidyr::expand_grid(
  xcoord = seq(min(X$xcoord), max(X$xcoord)), 
  ycoord = seq(min(X$ycoord),max(X$ycoord))
  ) %>%    
  dplyr::left_join(X, by=c('xcoord','ycoord'))
gg2 <- ggplot(X2) + geom_tile(aes(x = xcoord, y = ycoord, fill = value))
ggplotly(gg2)
geom2trace.GeomTile <- function(data, params, p) {
  x <- sort(unique(data[["x"]]))
  y <- sort(unique(data[["y"]]))
  # make sure we're dealing with a complete grid
  g <- expand.grid(x = x, y = y)
  g$order <- seq_len(nrow(g))
  g <- merge(g, data, by = c("x", "y"), all.x = TRUE)
  g <- g[order(g$order), ]
...
ggplot(g, aes(x = x, y = y, fill = value)) + geom_tile()
set.seed(1)
X1 <- data.frame(xcoord = c(sample(1:10, n, replace = TRUE), 1:10),
                ycoord = c(sample(1:10, n, replace = TRUE), 1:10),
                value = c(runif(n), rep(NA, 10)))
gg1 <- ggplot(X1) + geom_tile(aes(x = xcoord, y = ycoord, fill = value))
ggplotly(gg1)
# X: original dataframe as defined in the question
X2 <- tidyr::expand_grid(
  xcoord = seq(min(X$xcoord), max(X$xcoord)), 
  ycoord = seq(min(X$ycoord),max(X$ycoord))
  ) %>%    
  dplyr::left_join(X, by=c('xcoord','ycoord'))
gg2 <- ggplot(X2) + geom_tile(aes(x = xcoord, y = ycoord, fill = value))
ggplotly(gg2)
geom2trace.GeomTile <- function(data, params, p) {
  x <- sort(unique(data[["x"]]))
  y <- sort(unique(data[["y"]]))
  # make sure we're dealing with a complete grid
  g <- expand.grid(x = x, y = y)
  g$order <- seq_len(nrow(g))
  g <- merge(g, data, by = c("x", "y"), all.x = TRUE)
  g <- g[order(g$order), ]
...
ggplot(g, aes(x = x, y = y, fill = value)) + geom_tile()
set.seed(1)
X1 <- data.frame(xcoord = c(sample(1:10, n, replace = TRUE), 1:10),
                ycoord = c(sample(1:10, n, replace = TRUE), 1:10),
                value = c(runif(n), rep(NA, 10)))
gg1 <- ggplot(X1) + geom_tile(aes(x = xcoord, y = ycoord, fill = value))
ggplotly(gg1)
# X: original dataframe as defined in the question
X2 <- tidyr::expand_grid(
  xcoord = seq(min(X$xcoord), max(X$xcoord)), 
  ycoord = seq(min(X$ycoord),max(X$ycoord))
  ) %>%    
  dplyr::left_join(X, by=c('xcoord','ycoord'))
gg2 <- ggplot(X2) + geom_tile(aes(x = xcoord, y = ycoord, fill = value))
ggplotly(gg2)

Plotly Python update figure with dropMenu

copy iconCopydownload iconDownload
import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd

symbols = ['AAPL','GOOG','TSLA']
stocks = pd.DataFrame()
for s in symbols:
    data = yf.download(s, start="2021-01-01", end="2021-12-31")
    data['mean'] = data['Close'].rolling(20).mean()
    data['std'] = data['Close'].rolling(20).std()
    data['upperBand'] = data['mean'] + (data['std'] * 2)
    data.reset_index(inplace=True)
    data['symbol'] = s
    stocks = stocks.append(data, ignore_index=True)

def make_multi_plot(df):
    
    fig = make_subplots(rows=2, cols=1,
                        shared_xaxes=True,
                        vertical_spacing=0.03,
                        subplot_titles=('OHLC', 'Volume Profile'),
                        row_width=[0.2, 0.7])

    for s in df.symbol.unique():
        trace1 = go.Candlestick(
            x=df.loc[df.symbol.isin([s])].Date,
            open=df.loc[df.symbol.isin([s])].Open,
            high=df.loc[df.symbol.isin([s])].High,
            low=df.loc[df.symbol.isin([s])].Low,
            close=df.loc[df.symbol.isin([s])].Close,
            name=s)
        fig.append_trace(trace1,1,1)
        
        trace2 = go.Scatter(
            x=df.loc[df.symbol.isin([s])].Date,
            y=df.loc[df.symbol.isin([s])].upperBand,
            name=s)
        fig.append_trace(trace2,1,1)
        
        trace3 = go.Bar(
            x=df.loc[df.symbol.isin([s])].Date,
            y=df.loc[df.symbol.isin([s])].Volume,
            name=s)
        fig.append_trace(trace3,2,1)
        # fig.update_layout(title_text=s)
    
    # Calculate the total number of graphs
    graph_cnt=len(fig.data)
    # Number of Symbols
    symbol_cnt =len(df.symbol.unique())
    # Number of graphs per symbol
    tr = 3
    # Hide setting for initial display
    for g in range(tr, graph_cnt): 
        fig.update_traces(visible=False, selector=g)

    def create_layout_button(k, symbol):
        start, end = tr*k, tr*k+2
        visibility = [False]*tr*symbol_cnt
        # Number of graphs per symbol, so if you add a graph, add True.
        visibility[start:end] = [True,True,True]
        return dict(label = symbol,
                    method = 'restyle',
                    args = [{'visible': visibility[:-1],
                             'title': symbol,
                             'showlegend': True}])    
    
    fig.update(layout_xaxis_rangeslider_visible=False)
    fig.update_layout(
        updatemenus=[go.layout.Updatemenu(
            active = 0,
            buttons = [create_layout_button(k, s) for k, s in enumerate(df.symbol.unique())]
            )
        ])
    
    fig.show()
    return fig.layout
    
make_multi_plot(stocks)

Plotly dash table add rows and update input data

copy iconCopydownload iconDownload
@app.callback(
Output('table-container_3', 'data'),
Input('add_row', 'n_clicks'),
[State('table-container_3', 'data'),
State('table-container_3', 'columns')]+
[State('my_{}'.format(x), 'value') for x in input_types])
def add_row(n_clicks, rows, columns, selected_number, selected_pw,
            selected_text, selected_tel,
            selected_email, selected_url,
            selected_search):

if n_clicks > 0:
    rows.append({c['id']: r for c,r in zip(columns, [selected_number, selected_pw, selected_text, selected_tel, selected_email, selected_url, selected_search])})

return rows

Avoid legend duplication in plotly conversion from ggplot with facet_wrap

copy iconCopydownload iconDownload
library(plotly)
library(ggplot2)

p <- mpg %>% 
  ggplot(aes(year)) +
  geom_ribbon(aes(ymin=cty, ymax=hwy, fill = manufacturer), alpha=0.2) + 
  geom_line(aes(y = hwy, col=manufacturer))  +
  facet_wrap(~class)

gp <- ggplotly(p = p)

# Get the names of the legend entries
df <- data.frame(id = seq_along(gp$x$data), legend_entries = unlist(lapply(gp$x$data, `[[`, "name")))
# Extract the group identifier
df$legend_group <- gsub("^\\((.*?),\\d+\\)", "\\1", df$legend_entries)
# Add an indicator for the first entry per group
df$is_first <- !duplicated(df$legend_group)

for (i in df$id) {
  # Is the layer the first entry of the group?
  is_first <- df$is_first[[i]]
  # Assign the group identifier to the name and legendgroup arguments
  gp$x$data[[i]]$name <- df$legend_group[[i]]
  gp$x$data[[i]]$legendgroup <- gp$x$data[[i]]$name
  # Show the legend only for the first layer of the group 
  if (!is_first) gp$x$data[[i]]$showlegend <- FALSE
}
gp
library(plotly)
library(ggplot2)
library(purrr)
library(stringr)

p <- mpg %>% 
  ggplot(aes(year)) +
  geom_ribbon(aes(ymin=cty, ymax=hwy, fill = manufacturer), alpha=0.2) + 
  geom_line(aes(y = hwy, col=manufacturer))  +
  facet_wrap(~class)

gp <- ggplotly(p = p)

clean_pltly_legend <- function(.pltly_obj, .new_legend = c()) {
  # Cleans up a plotly object legend, particularly when ggplot is facetted
  
  assign_leg_grp <- function(.legend_group, .leg_nms) {
    # Assigns a legend group from the list of possible entries
    # Used to modify the legend settings for a plotly object
    
    leg_nms_rem <- .leg_nms
    
    parse_leg_nms <- function(.leg_options) {
      # Assigns a .leg_name, if possible
      # .leg_options is a 2-element list: 1 = original value; 2 = remaining options
      
      if (is.na(.leg_options)) {
        .leg_options
      } else if(length(leg_nms_rem) == 0) {
        # No more legend names to assign
        .leg_options
      } else {
        # Transfer the first element of the remaining options
        leg_nm_new <- leg_nms_rem[[1]]
        leg_nms_rem <<- leg_nms_rem[-1]
        
        leg_nm_new
      }
      
    }
    
    .legend_group %>% 
      map(~ parse_leg_nms(.))
    
  }
  
  simplify_leg_grps <- function(.legendgroup_vec) {
    # Simplifies legend groups by removing brackets, position numbers and then de-duplicating
    
    leg_grp_cln <-
      map_chr(.legendgroup_vec, ~ str_replace_all(., c("^\\(" = "", ",\\d+\\)$" = "")))
    
    modify_if(leg_grp_cln, duplicated(leg_grp_cln), ~ NA_character_)
    
  }
  
  pltly_obj_data <-
    .pltly_obj$x$data
  
  pltly_leg_grp <-
    # pltly_leg_grp is a character vector where each element represents a legend group. Element is NA if legend group not required or doesn't exist
    pltly_obj_data%>% 
    map(~ pluck(., "legendgroup")) %>% 
    map_chr(~ if (is.null(.)) {NA_character_} else {.}) %>%
    # Elements where showlegend = FALSE have legendgroup = NULL. 
    
    simplify_leg_grps() %>% 
    
    assign_leg_grp(.new_legend) 
  
  pltly_obj_data_new <-
    pltly_obj_data %>% 
    map2(pltly_leg_grp, ~ list_modify(.x, legendgroup = .y)) %>%
    map2(pltly_leg_grp, ~ list_modify(.x, name = .y)) %>%
    map2(pltly_leg_grp, ~ list_modify(.x, showlegend = !is.na(.y)))
  # i.e. showlegend set to FALSE when is.na(pltly_leg_grp), TRUE when not is.na(pltly_leg_grp)
  
  .pltly_obj$x$data <- pltly_obj_data_new
  
  .pltly_obj
  
}

clean_pltly_legend(gp)

How to share a dynamically generated image from react with react-share?

copy iconCopydownload iconDownload
import { useEffect, useRef, useState } from "react";
import { FacebookIcon, FacebookShareButton } from "react-share";

async function getUrFromService(): Promise<string> {
  // The real implementation would make a network call here.
  await new Promise((resolve) => setTimeout(resolve, 1000));
  return "https://via.placeholder.com/150";
}

export default function App() {
  const shareButton = useRef<HTMLButtonElement>(null);
  const [url, setUrl] = useState<string>("none"); // Unfortunately, we have to have a dummy string here, or FacebookShareButton will blow up.

  // Provide an onClick handler that asyncronously fetches the url and sets it in the state.
  const onClick = async () => {
    // Be sure to check for the "none" state, so we don't trigger an infinite loop.
    if (url === "none") {
      const newUrl = await getUrFromService();
      setUrl(newUrl);
    }
  };

  // Whenever "url" changes and we re-render, we manually fire the click event on the button, and then re-set the url.
  useEffect(() => {
    if (url !== "none") {
      shareButton.current?.click();
      setUrl("none");
    }
  }, [url, shareButton]);

  return (
    <FacebookShareButton
      ref={shareButton}
      // Disable calling the dialog if we don't have a url yet.
      openShareDialogOnClick={url !== "none"}
      url={url}
      onClick={onClick}
    >
      <FacebookIcon />
    </FacebookShareButton>
  );
}

//AsyncShareLoader.jsx
const AsyncShareLoader = ({ url, children }) => {
  const loading = !url;
  return (
    <div style={{ filter: `grayscale(${loading ? "100%" : "0%"}` }}>
      {React.Children.map(children, (child) =>
        React.cloneElement(child, {
          disabled: loading,
          url: loading ? "none" : url,
          openShareDialogOnClick: !loading
        })
      )}
    </div>
  );
};
const Share = () => {
  const [url, setUrl] = useState()

  useEffect(() => {
    fetch('/imgUrl').then(getUrlFromRes).then(setUrl)
  }, [])

  return (
    <AsyncShareLoader url={url}>
      <FacebookShareButton>
        <FacebookIcon />
      </FacebookShareButton>
    </AsyncShareLoader>    
  );
}
//AsyncShareLoader.jsx
const AsyncShareLoader = ({ url, children }) => {
  const loading = !url;
  return (
    <div style={{ filter: `grayscale(${loading ? "100%" : "0%"}` }}>
      {React.Children.map(children, (child) =>
        React.cloneElement(child, {
          disabled: loading,
          url: loading ? "none" : url,
          openShareDialogOnClick: !loading
        })
      )}
    </div>
  );
};
const Share = () => {
  const [url, setUrl] = useState()

  useEffect(() => {
    fetch('/imgUrl').then(getUrlFromRes).then(setUrl)
  }, [])

  return (
    <AsyncShareLoader url={url}>
      <FacebookShareButton>
        <FacebookIcon />
      </FacebookShareButton>
    </AsyncShareLoader>    
  );
}

Community Discussions

Trending Discussions on plotly
  • Dash ImportError: cannot import name 'get_current_traceback' from 'werkzeug.debug.tbtools'
  • R plotly separate functional legends
  • User inputs for R ggplot or plotly without shiny
  • Adding Contour Lines to 3D Plots
  • TypeError: load() missing 1 required positional argument: 'Loader' in Google Colab
  • ggplot geom_tile is distorted in ggplotly
  • Plotly Python update figure with dropMenu
  • Plotly dash table add rows and update input data
  • Avoid legend duplication in plotly conversion from ggplot with facet_wrap
  • How to share a dynamically generated image from react with react-share?
Trending Discussions on plotly

QUESTION

Dash ImportError: cannot import name 'get_current_traceback' from 'werkzeug.debug.tbtools'

Asked 2022-Mar-30 at 07:41

I'm trying to run a simple dash app in a conda environment in Pycharm, however I'm running into the error in the title. Weirdly enough, I couldn't find a place on the internet which has a mention of this bug, except for here. The code is simple, as all I'm trying to run is a simple dashapp; code obtained the code from here. I have tried switching between python versions in conda (back and forth between python 3.9, 3.8 and 3.7) but the error seems to be persistent. I know I have also correctly installed all its dependencies as I'm not getting any import error. Would appreciate if anyone could help with this.

Edit: Versions of Dash installed, as requested by @coralvanda : dash_versions

Basically, I just did a pip install of everything so all the versions of packages are the latest.

Screenshot of a full traceback of the error: traceback

ANSWER

Answered 2022-Mar-29 at 03:40

I've been in the same problem.

Uninstall the wrong version with:

pip uninstall werkzeug

Install the right one with:

pip install -v https://github.com/pallets/werkzeug/archive/refs/tags/2.0.1.tar.gz

Source https://stackoverflow.com/questions/71654590

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install plotly

Or install the latest development version (on GitHub) via {remotes}:.

Support

Please read through our contributing guidelines. Included are directions for opening issues, asking questions, contributing changes to plotly, and our code of conduct.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

Share this Page

share link
Reuse Pre-built Kits with plotly
Consider Popular Data Visualization Libraries
Try Top Libraries by ropensci
Compare Data Visualization Libraries with Highest Support
Compare Data Visualization Libraries with Highest Quality
Compare Data Visualization Libraries with Highest Security
Compare Data Visualization Libraries with Permissive License
Compare Data Visualization Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.