绘制 Matplotlib 绘图时出错(缺少字体指标文件:cmss17)

发布于 2025-01-14 18:43:05 字数 8846 浏览 0 评论 0原文

我知道有一些与此相关的类似问题,但我完全不知道该怎么做。我在这方面绝对是新手,所以如果可能的话,分步指南将非常有帮助。 所以我一直尝试在Jupyter笔记本中编写一个简单的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
plt.rcParams.update({'font.size': 22})

zeta = np.arange(10**-6,10**4,1000)
N0 = 50
ns = 1-(3*(1+16*zeta*N0/3))/(N0*(1+8*zeta*N0))

plt.plot(zeta,ns)
plt.show()

这是我的代码。我收到以下错误:

FileNotFoundError                         Traceback (most recent call last)
~\anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

~\anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, base64, **kwargs)
    149         FigureCanvasBase(fig)
    150 
--> 151     fig.canvas.print_figure(bytes_io, **kw)
    152     data = bytes_io.getvalue()
    153     if fmt == 'svg':

~\anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
   2228                        else suppress())
   2229                 with ctx:
-> 2230                     self.figure.draw(renderer)
   2231 
   2232             if bbox_inches:

~\anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     72     @wraps(draw)
     73     def draw_wrapper(artist, renderer, *args, **kwargs):
---> 74         result = draw(artist, renderer, *args, **kwargs)
     75         if renderer._rasterizing:
     76             renderer.stop_rasterizing()

~\anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

~\anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   2788 
   2789             self.patch.draw(renderer)
-> 2790             mimage._draw_list_compositing_images(
   2791                 renderer, self, artists, self.suppressComposite)
   2792 

~\anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    130     if not_composite or not has_images:
    131         for a in artists:
--> 132             a.draw(renderer)
    133     else:
    134         # Composite any adjacent images together

~\anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

~\anaconda3\lib\site-packages\matplotlib\_api\deprecation.py in wrapper(*inner_args, **inner_kwargs)
    429                          else deprecation_addendum,
    430                 **kwargs)
--> 431         return func(*inner_args, **inner_kwargs)
    432 
    433     return wrapper

~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2919             renderer.stop_rasterizing()
   2920 
-> 2921         mimage._draw_list_compositing_images(renderer, self, artists)
   2922 
   2923         renderer.close_group('axes')

~\anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    130     if not_composite or not has_images:
    131         for a in artists:
--> 132             a.draw(renderer)
    133     else:
    134         # Composite any adjacent images together

~\anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

~\anaconda3\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs)
   1140 
   1141         ticks_to_draw = self._update_ticks()
-> 1142         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1143                                                                 renderer)
   1144 

~\anaconda3\lib\site-packages\matplotlib\axis.py in _get_tick_bboxes(self, ticks, renderer)
   1066     def _get_tick_bboxes(self, ticks, renderer):
   1067         """Return lists of bboxes for ticks' label1's and label2's."""
-> 1068         return ([tick.label1.get_window_extent(renderer)
   1069                  for tick in ticks if tick.label1.get_visible()],
   1070                 [tick.label2.get_window_extent(renderer)

~\anaconda3\lib\site-packages\matplotlib\axis.py in <listcomp>(.0)
   1066     def _get_tick_bboxes(self, ticks, renderer):
   1067         """Return lists of bboxes for ticks' label1's and label2's."""
-> 1068         return ([tick.label1.get_window_extent(renderer)
   1069                  for tick in ticks if tick.label1.get_visible()],
   1070                 [tick.label2.get_window_extent(renderer)

~\anaconda3\lib\site-packages\matplotlib\text.py in get_window_extent(self, renderer, dpi)
    901 
    902         with cbook._setattr_cm(self.figure, dpi=dpi):
--> 903             bbox, info, descent = self._get_layout(self._renderer)
    904             x, y = self.get_unitless_position()
    905             x, y = self.get_transform().transform((x, y))

~\anaconda3\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer)
    304 
    305         # Full vertical extent of font, including ascenders and descenders:
--> 306         _, lp_h, lp_d = renderer.get_text_width_height_descent(
    307             "lp", self._fontproperties,
    308             ismath="TeX" if self.get_usetex() else False)

~\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    227             texmanager = self.get_texmanager()
    228             fontsize = prop.get_size_in_points()
--> 229             w, h, d = texmanager.get_text_width_height_descent(
    230                 s, fontsize, renderer=self)
    231             return w, h, d

~\anaconda3\lib\site-packages\matplotlib\texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    399             dvifile = self.make_dvi(tex, fontsize)
    400             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
--> 401                 page, = dvi
    402             # A total height (including the descent) needs to be returned.
    403             return page.width, page.height + page.descent, page.descent

~\anaconda3\lib\site-packages\matplotlib\dviread.py in __iter__(self)
    249             integers.
    250         """
--> 251         while self._read():
    252             yield self._output()
    253 

~\anaconda3\lib\site-packages\matplotlib\dviread.py in _read(self)
    329         while True:
    330             byte = self.file.read(1)[0]
--> 331             self._dtable[byte](self, byte)
    332             downs += self._dtable[byte].__name__ == "_down"
    333             if (self._baseline_v is None

~\anaconda3\lib\site-packages\matplotlib\dviread.py in wrapper(self, byte)
    172             if state is not None and self.state != state:
    173                 raise ValueError("state precondition failed")
--> 174             return method(self, *[f(self, byte-min) for f in get_args])
    175         if max is None:
    176             table[min] = wrapper

~\anaconda3\lib\site-packages\matplotlib\dviread.py in _fnt_def(self, k, c, s, d, a, l)
    474     @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
    475     def _fnt_def(self, k, c, s, d, a, l):
--> 476         self._fnt_def_real(k, c, s, d, a, l)
    477 
    478     def _fnt_def_real(self, k, c, s, d, a, l):

~\anaconda3\lib\site-packages\matplotlib\dviread.py in _fnt_def_real(self, k, c, s, d, a, l)
    481         tfm = _tfmfile(fontname)
    482         if tfm is None:
--> 483             raise FileNotFoundError("missing font metrics file: %s" % fontname)
    484         if c != 0 and tfm.checksum != 0 and c != tfm.checksum:
    485             raise ValueError('tfm checksum mismatch: %s' % n)

FileNotFoundError: missing font metrics file: cmss17

我不确定是否应该将整个错误放在这里,但这就是我尝试绘制图表时得到的结果。我唯一能想到的是,一些用于在图表上写入内容的文件丢失了,但我不知道如何解决这个问题。任何帮助将不胜感激。 谢谢。

I know there are a few similar questions related to this but I have absolutely no idea on what to do. I am absolutely a newbie when it comes to this so if possible a step-by-step guide would be extremely helpful.
So I have been trying to write a simple code in Jupyter notebook:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
plt.rcParams.update({'font.size': 22})

zeta = np.arange(10**-6,10**4,1000)
N0 = 50
ns = 1-(3*(1+16*zeta*N0/3))/(N0*(1+8*zeta*N0))

plt.plot(zeta,ns)
plt.show()

This is my code. And I am getting the following error:

FileNotFoundError                         Traceback (most recent call last)
~\anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

~\anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, base64, **kwargs)
    149         FigureCanvasBase(fig)
    150 
--> 151     fig.canvas.print_figure(bytes_io, **kw)
    152     data = bytes_io.getvalue()
    153     if fmt == 'svg':

~\anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
   2228                        else suppress())
   2229                 with ctx:
-> 2230                     self.figure.draw(renderer)
   2231 
   2232             if bbox_inches:

~\anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     72     @wraps(draw)
     73     def draw_wrapper(artist, renderer, *args, **kwargs):
---> 74         result = draw(artist, renderer, *args, **kwargs)
     75         if renderer._rasterizing:
     76             renderer.stop_rasterizing()

~\anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

~\anaconda3\lib\site-packages\matplotlib\figure.py in draw(self, renderer)
   2788 
   2789             self.patch.draw(renderer)
-> 2790             mimage._draw_list_compositing_images(
   2791                 renderer, self, artists, self.suppressComposite)
   2792 

~\anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    130     if not_composite or not has_images:
    131         for a in artists:
--> 132             a.draw(renderer)
    133     else:
    134         # Composite any adjacent images together

~\anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

~\anaconda3\lib\site-packages\matplotlib\_api\deprecation.py in wrapper(*inner_args, **inner_kwargs)
    429                          else deprecation_addendum,
    430                 **kwargs)
--> 431         return func(*inner_args, **inner_kwargs)
    432 
    433     return wrapper

~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in draw(self, renderer, inframe)
   2919             renderer.stop_rasterizing()
   2920 
-> 2921         mimage._draw_list_compositing_images(renderer, self, artists)
   2922 
   2923         renderer.close_group('axes')

~\anaconda3\lib\site-packages\matplotlib\image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    130     if not_composite or not has_images:
    131         for a in artists:
--> 132             a.draw(renderer)
    133     else:
    134         # Composite any adjacent images together

~\anaconda3\lib\site-packages\matplotlib\artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     49                 renderer.start_filter()
     50 
---> 51             return draw(artist, renderer, *args, **kwargs)
     52         finally:
     53             if artist.get_agg_filter() is not None:

~\anaconda3\lib\site-packages\matplotlib\axis.py in draw(self, renderer, *args, **kwargs)
   1140 
   1141         ticks_to_draw = self._update_ticks()
-> 1142         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1143                                                                 renderer)
   1144 

~\anaconda3\lib\site-packages\matplotlib\axis.py in _get_tick_bboxes(self, ticks, renderer)
   1066     def _get_tick_bboxes(self, ticks, renderer):
   1067         """Return lists of bboxes for ticks' label1's and label2's."""
-> 1068         return ([tick.label1.get_window_extent(renderer)
   1069                  for tick in ticks if tick.label1.get_visible()],
   1070                 [tick.label2.get_window_extent(renderer)

~\anaconda3\lib\site-packages\matplotlib\axis.py in <listcomp>(.0)
   1066     def _get_tick_bboxes(self, ticks, renderer):
   1067         """Return lists of bboxes for ticks' label1's and label2's."""
-> 1068         return ([tick.label1.get_window_extent(renderer)
   1069                  for tick in ticks if tick.label1.get_visible()],
   1070                 [tick.label2.get_window_extent(renderer)

~\anaconda3\lib\site-packages\matplotlib\text.py in get_window_extent(self, renderer, dpi)
    901 
    902         with cbook._setattr_cm(self.figure, dpi=dpi):
--> 903             bbox, info, descent = self._get_layout(self._renderer)
    904             x, y = self.get_unitless_position()
    905             x, y = self.get_transform().transform((x, y))

~\anaconda3\lib\site-packages\matplotlib\text.py in _get_layout(self, renderer)
    304 
    305         # Full vertical extent of font, including ascenders and descenders:
--> 306         _, lp_h, lp_d = renderer.get_text_width_height_descent(
    307             "lp", self._fontproperties,
    308             ismath="TeX" if self.get_usetex() else False)

~\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in get_text_width_height_descent(self, s, prop, ismath)
    227             texmanager = self.get_texmanager()
    228             fontsize = prop.get_size_in_points()
--> 229             w, h, d = texmanager.get_text_width_height_descent(
    230                 s, fontsize, renderer=self)
    231             return w, h, d

~\anaconda3\lib\site-packages\matplotlib\texmanager.py in get_text_width_height_descent(self, tex, fontsize, renderer)
    399             dvifile = self.make_dvi(tex, fontsize)
    400             with dviread.Dvi(dvifile, 72 * dpi_fraction) as dvi:
--> 401                 page, = dvi
    402             # A total height (including the descent) needs to be returned.
    403             return page.width, page.height + page.descent, page.descent

~\anaconda3\lib\site-packages\matplotlib\dviread.py in __iter__(self)
    249             integers.
    250         """
--> 251         while self._read():
    252             yield self._output()
    253 

~\anaconda3\lib\site-packages\matplotlib\dviread.py in _read(self)
    329         while True:
    330             byte = self.file.read(1)[0]
--> 331             self._dtable[byte](self, byte)
    332             downs += self._dtable[byte].__name__ == "_down"
    333             if (self._baseline_v is None

~\anaconda3\lib\site-packages\matplotlib\dviread.py in wrapper(self, byte)
    172             if state is not None and self.state != state:
    173                 raise ValueError("state precondition failed")
--> 174             return method(self, *[f(self, byte-min) for f in get_args])
    175         if max is None:
    176             table[min] = wrapper

~\anaconda3\lib\site-packages\matplotlib\dviread.py in _fnt_def(self, k, c, s, d, a, l)
    474     @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
    475     def _fnt_def(self, k, c, s, d, a, l):
--> 476         self._fnt_def_real(k, c, s, d, a, l)
    477 
    478     def _fnt_def_real(self, k, c, s, d, a, l):

~\anaconda3\lib\site-packages\matplotlib\dviread.py in _fnt_def_real(self, k, c, s, d, a, l)
    481         tfm = _tfmfile(fontname)
    482         if tfm is None:
--> 483             raise FileNotFoundError("missing font metrics file: %s" % fontname)
    484         if c != 0 and tfm.checksum != 0 and c != tfm.checksum:
    485             raise ValueError('tfm checksum mismatch: %s' % n)

FileNotFoundError: missing font metrics file: cmss17

I am not sure if I should be placing the whole error here but this is what I am getting when I try plotting the graph. The only thing which I could think of is the fact that some file which is used to write things on the graph is missing but I don't know how to resolve this. Any help would be appreciated.
Thank You.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

朕就是辣么酷 2025-01-21 18:43:05

我刚刚遇到了同样的错误,就我而言,我需要使用乳胶。我发现,如果正确安装了其他字体,更改默认字体可以解决该问题:

plt.rcParams.update({
"text.usetex": True,
"font.family": "sans-serif",
"font.sans-serif": ["Helvetica"]})

您可以在代码的第 6 行插入此脚本,看看是否有帮助。

I just came across the same error, in my case I needed to use latex. I found out that if other fonts are correctly installed, changing the default font can resolve the issue:

plt.rcParams.update({
"text.usetex": True,
"font.family": "sans-serif",
"font.sans-serif": ["Helvetica"]})

You could insert this script at line 6 of your code and see if it helps.

不爱素颜 2025-01-21 18:43:05

我没有从您发布的内容中得出您想要的字体大小 22,因此这适用于轴刻度的标签。
您发布的内容的简单版本:

import numpy as np
import matplotlib.pyplot as plt

zeta = np.arange(10**-6,10**4,1000)
N0 = 50
ns = 1-(3*(1+16*zeta*N0/3))/(N0*(1+8*zeta*N0))
plt.plot(zeta,ns)
plt.tick_params(labelsize=22)
plt.show()

您可以在我的评论中转到此处,会话启动后打开笔记本,并在那里测试该代码。您应该会看到它应该有效。如果它的工作方式与您尝试的方式不同,那么您的东西就已经过时了。

刻度格式基础知识在 Matplotlib 的顶部进行了说明在第一个代码块中勾选格式化程序文档。在大多数情况下,您不再需要 rcrcParams 。现在语法更加明显了。使用它的任何答案要么已经过时,因为它们没有使用提供的路线,要么它们涵盖了异常/边缘情况。

I didn't follow from what you posted what you were looking to be font size 22, and so this does it for the labels of the axis ticks.
Simpler version of what you posted:

import numpy as np
import matplotlib.pyplot as plt

zeta = np.arange(10**-6,10**4,1000)
N0 = 50
ns = 1-(3*(1+16*zeta*N0/3))/(N0*(1+8*zeta*N0))
plt.plot(zeta,ns)
plt.tick_params(labelsize=22)
plt.show()

You can go to here in my comment, open a notebook after the session spins up, and test that code there. You should see it should work. If it doesn't work the same way where you are trying you have something out of date.

The tick formatting basics are illustrated right at the top of Matplotlib's tick formatters documentation in the first block of code. You shouldn't need rc or rcParams any longer in most cases. The syntax is much more obvious now. Any answers using that are either outdated as they aren't using the provided routes or they are covering unusual / edge cases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文