Skip to content

Dashboard with plotly cuts the legends in preview #8612

Open

Description

@fkgruber

Bug description

I used quarto preview file.qmd

legends get cut even if I put it in the middle of the plot:

image

Steps to reproduce

---
# YAML header created by ox-ravel
format: dashboard
embed-resources: true
title: quarto plotly
author: .
---


# Test


## Column {.tabset scrolling=True}


### head1 {scrolling=True, .flow}


#### Rows {scrolling=False}



##### Column

::: {.card title="PR"}

```{python}
#| echo: FALSE
#| eval: TRUE
#| results: 'hide'
#| message: FALSE
#| warning: FALSE
#| error: FALSE
#| cache: FALSE
#| fig.width: 10
#| fig.height: 10
#| autodep: TRUE
import pandas as pd
import numpy as np
from sklearn.metrics import precision_recall_curve, roc_curve
import plotly.express as px
y_true = np.array([0, 0, 1, 1])
y_scores = np.array([0.1, 0.4, 0.35, 0.8])
precision, recall, thresholds = precision_recall_curve( y_true, y_scores)
y_true2 = np.array([1, 0, 0, 1,0,1])
y_scores2 = np.array([0.9, 0.34, 0.35, 0.1,0.9,0.9])
precision2, recall2, thresholds2 = precision_recall_curve( y_true2, y_scores2)
toplot=pd.concat(
    [pd.DataFrame({'precision':precision,'recall':recall,"algorithm":"algorighm 1 auc=0.3"}),
    pd.DataFrame({'precision':precision2,'recall':recall2,"algorithm":"algoritm 2 auc =0.9"})]
    )
px.line(toplot,
        x='recall',
        y='precision',
        color='algorithm',
        template="plotly_white"
        ).show()
```

:::

::: {.card title="ROC"}
this shows…

```{python}
#| echo: FALSE
#| eval: TRUE
#| results: 'hide'
#| message: FALSE
#| warning: FALSE
#| error: FALSE
#| cache: FALSE
#| fig.width: 10
#| fig.height: 10
#| autodep: TRUE
fpr, tpr, thresholds = roc_curve( y_true, y_scores)
fpr2, tpr2, thresholds2 = roc_curve( y_true2, y_scores2)

toplot2=pd.concat(
    [pd.DataFrame({'fpr':fpr,'tpr':tpr,"algorithm":"algorithm 1 auc 0.3"}),
    pd.DataFrame({'fpr':fpr2,'tpr':tpr2,"algorithm":"algorightm 2 auc 0.1"})]
    )

fig=px.line(toplot2,
        x='fpr',
        y='tpr',
        color='algorithm',
        template="plotly_white"
        )
fig.update_layout(legend=dict(
         yanchor="top",
         y=1,
         xanchor="left",
         x=0.3
      )
    )
```

:::

Expected behavior

see the complete legend

Actual behavior

legend get cuts.
inspect shows a warning
image

Your environment

No response

Quarto check output

No response

Activity

  1. added
    bug
    on Feb 5, 2024
  2. fkgruber commented on Feb 5, 2024

    @fkgruber
    ContributorAuthor

    by the way I see this problem sometimes with quarto render as well. unfortunately I don't have a replicable example
    In those cases I see messages like

    Deprecated feature used
    Specifying overflow: visible on img, video and canvas tags may cause them to produce visual content outside of the element bounds. See https://github.com/WICG/shared-element-transitions/blob/main/debugging_overflow_on_images.md .
    1 source

    thanks
    FKG

  3. added
    third-party
    on Feb 11, 2024
  4. xSardine commented on Mar 4, 2024

    @xSardine

    I am encountering the same issue. When I open the HTML in Firefox, everything functions correctly. However, when I attempt to open it in a Chromium-based browser such as Chrome or Brave, the legends are truncated. I do not see any errors during rendering or within the browser console.

    For reference, here is the code: https://github.com/xSardine/stats.anisongdb. I can provide a minimal data sample to run that code if necessary, but I believe the example provided above is enough.

    I instead shared this repository because after further testing :

    • It seems that when accessing the dashboard via the GitHub Pages URL, initially, there appear to be no issues (for instance, when using a private window). However, after reloading the page, the display errors resurface. At first, I suspected a caching issue, but even after disabling the cache, reloading the page continues to yield display errors. I am not sure what could cause this behaviour.

    • When I try the same thing locally using Quarto render, I am unable to replicate this behavior (the display error is always there)

    Firefox works both locally and on github-pages

  5. cderv commented on Mar 4, 2024

    @cderv
    Member

    @xSardine I don't see any error in https://xsardine.github.io/stats.anisongdb/ but I may have missed it. I opened with Chrome on Windows. Can you tell more precisely where you see the same error ?

    I did not try locally yet. EDIT: in fact, we can't run locally because files are not in project (../data/raw/).

  6. xSardine commented on Mar 4, 2024

    @xSardine

    Thanks for the swift reply @cderv

    I've included sample datasets within the repository so that others can run the code locally.

    Regarding browser versions :

    • Chrome: Version 114.0.5735.90 (Official Build) (64-bit)
    • Brave: Version 1.62.153 Chromium: 121.0.6167.85 (Official Build) (64-bit)

    This for my Ubuntu environment, but I've been having the same issue on Windows. I also tried from my smartphone, and the same visual bug is occuring.

    The condition for the display error not occurring on my end seems very specific. I've found that the legends display properly with the following methods :

    • Opening the link for the first time in a private navigation window.
    • When I open the link in a new tab (using the mouse scroll button). (??!)
    • Edit: After trying again, disabling cache makes the legends display properly this time, so this could be a caching issue as I first suspected ? I don't know why yesterday it wasn't working even after disabling it...
    • Edit of edit : This is on Brave on Windows, on my chrome browser on Ubuntu, the reverse is happening : if I disable the cache, it's not working, but if I keep it, it is working... I suspect this is a problem of library initialization timing ? This is the only thing that differ that I can see between all those environments.

    Accessing the link directly within the tab, or after reloading the page, or locally using quarto preview results in the legends being cut off. Here's an example with one of the graphs (but it's on every graph) comparing with and without the visual bug :

    To be honest, it looks more of a problem with plotly renderers having a weird behaviour with my browsers rather than an issue directly related to Quarto. But it only happen when using dashboards..

  7. lostmygithubaccount commented on Mar 4, 2024

    @lostmygithubaccount

    just want to chime in and mention I've seen this as well with Quarto dashboards and plotly plots, where the legend is cutoff on the right, using Edge (chromium-based)

  8. cderv commented on Mar 4, 2024

    @cderv
    Member

    FWIW I can't reproduce with xsardine.github.io/stats.anisongdb on Chrome Windows Version 122.0.6261.95

    It always shows me the graph like the one on the right. I'll try with local version

  9. lostmygithubaccount commented on Mar 4, 2024

    @lostmygithubaccount
  10. cderv commented on Mar 4, 2024

    @cderv
    Member

    Thanks. This make another example.

    I'll try to reproduce locally - but it seems to be something with Plotly directly. In Dashboard context, the renderer is set to notebook while for non dashboard format we use notebook_connected as default (https://plotly.com/python/renderers/#interactive-renderers)

    I don't know if this could have an impact but this is one known difference between HTML format and Dashboard format.

  11. JRocki commented on Apr 18, 2024

    @JRocki

    I am also experiencing this issue for my Quarto Dashboard (using Chrome), but not when I do a Quarto notebook.

  12. Dariom92 commented on Apr 18, 2024

    @Dariom92

    I am also experiencing this issue on Chrome and Edge on windows on quarto version v1.4.553. Like others the notebook version of the plots are fine but not when rendered in the dashboards.

  13. mcanouil commented on Apr 19, 2024

    @mcanouil
    Collaborator

    The issue seems to be how Plotly sets the width, refreshing the page solves the issue at least it is what I have seen.
    How avoid this weird legend repositioning, I set the legend on top left.
    As far as i can tell, it only happens on the right edge.

  14. added this to the Future milestone on Jun 5, 2024
  15. Marcnuth commented on Jun 19, 2025

    @Marcnuth

    the issues still exists, any updates or plans?

  16. cderv commented on Jun 19, 2025

    @cderv
    Member

    As you can see, no update shared here, nor in Plotly repo issue. When there is an update we do share in the thread, so please no need to post comment like this. Thank you !

    However, if you want to help find the bottom issue and discuss a fix for plotly, we welcome any help ! Thanks.

  17. xSardine commented on Jul 1, 2025

    @xSardine

    I investigated the problem a bit, I am posting here because I was only able to reproduce it inside a Quarto dashboard environment. But most of my research was within the Plotly.js code (will link to this post in the issue there).

    The problem seems to be because the <g class="scrollbox"> element inside the infolayer has a clipPath with an incorrectly small width. Specifically, the clipping rectangle’s width is set using:

    clipPath.select("rect").attr({
      width: legendObj._width - 2 * bw,
      height: height - 2 * bw,
      x: bw,
      y: bw,
    });

    In my case, legendObj._width is always 45 (probably a minimal default), and bw (border width) is 0. This results in the clipPath being too narrow, cutting off the legend text.

    Going up, legendObj._width is calculated in computeLegendDimensions. When isVertical is true, it’s defined like this, where d is iterating over the legend's traces (basically trying to get the longest trace attribute name) :

    legendObj._width = Math.max(legendObj._width, d[0].width);

    This is also 0 because d[0].width comes from computeTextDimensions, which uses:

    width = textNode ? Drawing.bBox(textNode).width : 0;

    However, Drawing.bBox(textNode).width returns 0, it may run too early, before the SVG elements are fully rendered and laid out ? I'm not sure why but anyway replacing that line with a direct DOM API call seems to fix it :

    width = textNode ? textNode.getBBox().width : 0;

    This correctly measures the text width, resulting in a proper legendObj._width, and fixes the clipping issue downstream.

    Edit : this was done in a minimal quarto example with just one graph, my temporary fix actually doesn't work perfectly : it only fixes the first iteration of the legend, unsure why, but this probably wasn't the best fix anyway since the root issue should be Drawing.bBox(textNode).width returning 0.

    Here is a minimal example that causes the issue for me :

    ---
    title: "Minimal Legends Cut Example"
    format: 
      dashboard:
        navbar: true
    jupyter: python3
    ---
    
    ```{python}
    import plotly.graph_objects as go
    import plotly.io as pio
    
    # Set the default renderer to notebook_connected so that I can manually change the source plotly.js used in the HTML output
    # This isn't necessary to cause the issue
    pio.renderers.default = "notebook_connected"
    
    types = ["Opening", "Ending", "Insert Song"]
    values = [120, 80, 25]
    colors = ["blue", "orangered", "green"]
    
    fig = go.Figure(
        data=[go.Pie(
            labels=types,
            values=values,
            hole=0.3,
            marker=dict(colors=colors, line=dict(color="#000000", width=1)),
        )]
    )
    
    fig.update_layout(
        title="Fake Song Type Distribution",
        legend=dict(x=0.8, y=0.8, title="My legend title"),
    )
    ```
  18. cderv commented on Jul 1, 2025

    @cderv
    Member

    Thanks a lot for this deep look into it. This type of community contribution really helps us. I'll see how I can leverage that when tackling this specific issue. Thanks.

  19. self-assigned this
    on Jul 1, 2025
  20. astrowonk commented on Aug 7, 2025

    @astrowonk

    This is happening to me consistently withquarto render. I have an MRE here where it happens both when the legend is on the right and moved to the top left.

    It's also happening live on a deployed dashboard at my site. I swear the legends worked 2 months ago when I first set that dashboard up, but trying with various permutations of quarto and plotly versions didn't change anything. I posted a few more details on the plotly issue.

  21. beyondsimulations commented on Aug 7, 2025

    @beyondsimulations

    I’m having the same issue, and somehow it didn’t happen at the end of 2024. Last October, I set up a dashboard with a working legend for a customer. But when I updated the dashboard with new data last week, the issue also popped up for me. However, I’m not sure which version of Quarto I used back then.

    Adding the following code snippet (based on the proposed solution from @xSardine - thanks!) at the beginning of the document serves as a temporary solution across several plots in the dashboard:

    <style>
    .legend .scrollbox {
      clip-path: none !important;
    }
    </style>

    However, you’ll need to set the background of the legend to be transparent for it to work, and the legend might occasionally intersect the actual plots. Still, it’s better than a cut-off legend and it works consistently across all plots for me.

  22. astrowonk commented on Aug 7, 2025

    @astrowonk

    I’m having the same issue, and somehow it didn’t happen at the end of 2024. Last October, I set up a dashboard with a working legend for a customer. But when I updated the dashboard with new data last week, the issue also popped up for me. However, I’m not sure which version of Quarto I used back then.

    Adding the following code snippet (based on the proposed solution from @xSardine - thanks!) at the beginning of the document serves as a temporary solution across several plots in the dashboard:

    <style> .legend .scrollbox { clip-path: none !important; } </style>

    However, you’ll need to set the background of the legend to be transparent for it to work, and the legend might occasionally intersect the actual plots. Still, it’s better than a cut-off legend and it works consistently across all plots for me.

    Oh that's super helpful! I added it and did this in the YAML:

    include-before-body: 
      text: |
        <style>
          .legend .scrollbox {
            clip-path: none !important;
            }
          g.legend rect.bg {fill-opacity: 0 !important;}
        </style>

    The g.legend rect.bg {fill-opacity: 0 !important;} part sets the background of the legend to be transparent as you mentioned. Not a perfect workraround, but better than the status quo!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugdashboardsplotlythird-party

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions