How can I center align a python generated Poltly figure when using html format? #13791
Answered
by
mcanouil
meggitt-vibro
asked this question in
Q&A
-
DescriptionI am trying to center align a plotly figure generated by a python code block. No matter what i try to do, the figure remains left aligned. On the other hand, figures generated by matplotlib and centered with no problems. The MWE below reproduced the issue for me. Any help would be appreciated! (Using Quarto 1.7.31 and running on macOS 26.0.1) ---
title: "Minimal working example of plotly figure not centering"
format: html
authors:
- name: Joe Bloggs
---
::: {.center}
```{python}
#| label: fig-plot
#| fig-cap: "This is a caption."
#| eval: true
#| echo: true
import numpy as np
import plotly.graph_objects as go
x = np.linspace(-2, 2, 200)
y = np.linspace(-2, 2, 200)
X, Y = np.meshgrid(x,y)
fig = go.Figure(data =
go.Surface(x=X, y=Y, z=np.real(np.sin(X)*np.sin(Y)), colorscale='Viridis', showscale=False))
fig.update_layout(autosize=True,
width=500, height=500,
margin=dict(l=20, r=20, b=20, t=40)
)
```
:::
|
Beta Was this translation helpful? Give feedback.
Answered by
mcanouil
Dec 12, 2025
Replies: 1 comment 1 reply
-
|
I believe this to be an issue with plotly itself as if you use your favourite browser and inspect the figure, you can see the HTML/CSS structure. ---
title: "Minimal working example of plotly figure not centering"
format:
html:
include-in-header:
- text: |
<style>
figure > div:has(.plotly-graph-div) {
display: flex !important;
justify-content: center !important;
}
.plotly-graph-div {
margin-left: auto !important;
margin-right: auto !important;
display: block !important;
}
</style>
---
```{python}
# | label: fig-plot
# | fig-cap: "This is a caption."
# | eval: true
# | echo: true
import numpy as np
import plotly.graph_objects as go
x = np.linspace(-2, 2, 200)
y = np.linspace(-2, 2, 200)
X, Y = np.meshgrid(x, y)
fig = go.Figure(data=go.Surface(x=X, y=Y, z=np.real(np.sin(X) * np.sin(Y)), colorscale="Viridis", showscale=False))
fig.update_layout(autosize=True, width=500, height=500, margin=dict(l=20, r=20, b=20, t=40))
``` |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
meggitt-vibro
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe this to be an issue with plotly itself as if you use your favourite browser and inspect the figure, you can see the HTML/CSS structure.
You can override with something like: