daskol / typst-mpl-backend

Typst backend for matplotlib (Python visualization library).
MIT License
8 stars 1 forks source link

Error when saving a figure #3

Open fredericjs opened 1 month ago

fredericjs commented 1 month ago

Nice project! When I try to save this example from the matplotlib gallery (https://matplotlib.org/stable/gallery/lines_bars_and_markers/csd_demo.html#sphx-glr-gallery-lines-bars-and-markers-csd-demo-py) using your backend, I get the following error:

File [~\AppData\Local\Programs\Python\Python312\Lib\encodings\cp1252.py:19](http://localhost:8888/~/AppData/Local/Programs/Python/Python312/Lib/encodings/cp1252.py#line=18), in IncrementalEncoder.encode(self, input, final)
     18 def encode(self, input, final=False):
---> 19     return codecs.charmap_encode(input,self.errors,encoding_table)[0]

UnicodeEncodeError: 'charmap' codec can't encode character '\u2212' in position 0: character maps to <undefined>

Here is the code that I ran:

import numpy as np
import matplotlib.pyplot as plt
import mpl_typst.as_default
fig, (ax1, ax2) = plt.subplots(2, 1, layout='constrained')

dt = 0.01
t = np.arange(0, 30, dt)

# Fixing random state for reproducibility
np.random.seed(19680801)

nse1 = np.random.randn(len(t))                 # white noise 1
nse2 = np.random.randn(len(t))                 # white noise 2
r = np.exp(-t / 0.05)

cnse1 = np.convolve(nse1, r, mode='same') * dt   # colored noise 1
cnse2 = np.convolve(nse2, r, mode='same') * dt   # colored noise 2

# two signals with a coherent part and a random part
s1 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse1
s2 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse2

ax1.plot(t, s1, t, s2)
ax1.set_xlim(0, 5)
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('s1 and s2')
ax1.grid(True)

cxy, f = ax2.csd(s1, s2, 256, 1. / dt)
ax2.set_ylabel('CSD (dB)')

fig.savefig('fig.typ')
daskol commented 1 month ago

Hm, it looks like Windows-specific issue (not CrowdStrike-like, lol). Maybe, non-utf8 text encoding causes the issue. I guess, on your system the default one is cp1252. Try to save the script in utf-8 and run again.