Plotly chart not working correcly with HTMX call
I've added HTMX to my Django project, and after that my plotly chart started glitching. I generate HTML for the chart with:
def get_chart(f, power, resolution):
import pandas as pd
yaxis_title = "Power, %"
try:
df = pd.read_csv(
os.path.join(settings.MEDIA_ROOT, f),
compression="zip",
sep=" ",
header=None,
names=["Date", "Val"],
)
if power and power != 100:
df.Val = df.Val.apply(lambda x: x * power / 100)
yaxis_title = "Power, kW"
fig = go.Figure(
data=[
go.Scatter(
x=df["Date"],
y=df["Val"],
),
],
)
fig.update_layout(
title="",
yaxis_title=yaxis_title,
hovermode="x unified",
width=resolution.value[0],
height=resolution.value[1],
margin=dict(
l=4,
r=4,
b=4,
t=40,
pad=4,
),
)
fig.update_yaxes(
fixedrange=False,
)
return fig.to_html(full_html=False, div_id="rtv-chart")
except (OSError, ValueError, BadZipFile) as e:
print(e)
return None
Which I send back with a view:
def chart(request, pk):
obj = RtvLog.objects.get(id=pk)
if res := request.GET.get("size"):
chart = get_chart(obj.log.file.name, obj.power, Resolution[res])
else:
chart = get_chart(obj.log.file.name, obj.power, Resolution.SVGA)
if chart:
return HttpResponse(chart, content_type="text/html")
return HttpResponse(status=404)
And then render in a template:
<div class="flex gap-4 w-fit">
<div hx-get="{% url 'tools:get_chart' object.id %}"
hx-trigger="load once, change from:#size"
hx-include="#size"
hx-indicator="#chart-indicator"
hx-target="this">
<div class="htmx-indicator"
id="chart-indicator">{% include "block-spinner.html" %}</div>
</div>
<fieldset id="size">
<legend>Select chart size:</legend>
{% for size in sizes %}
<div>
<input type="radio"
id="size_{{ size }}"
name="size"
value="{{ size }}"
{% if forloop.counter == 2 %}checked{% endif %} />
<label for="size_{{ size }}">{{ size }}</label>
</div>
{% endfor %}
</fieldset>
</div>
</div>
The first time it loads it works ok, except that control button are in weird positions. If I make another call (by triggering #size
) it renders the chart in a broken state: the buttons are now on the left, the Y-axis label and overlay (hover information and selection) is showing under the chart. If I try selecting something it will restore to the initial state (icons in the right corner, but still now in a row like they are supposed to be). And I also get this warning in console: WARN: Calling _doPlot as if redrawing but this container doesn't yet have a plot.