【问题标题】:Matplotlib "LinearSegmentedColormap" errorMatplotlib \"LinearSegmentedColormap\" 错误
【发布时间】:2022-12-11 17:11:24
【问题描述】:

有人可以帮我解决 matplotlib 的这个错误吗? 我正在将 jupyter 用于一本名著中的一些数据科学项目(动手机器学习......),但我遇到了一个异常错误的问题。

这是代码:

%matplotlib inline  
import matplotlib.pyplot as plt
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
             s=housing["population"]/100, label="population", figsize=(10,7),
             c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True,
             sharex=False)
plt.legend()
save_fig("housing_prices_scatterplot")

这是错误:

TypeError                                 Traceback (most recent call last)
Cell In [85], line 3
      1 get_ipython().run_line_magic('matplotlib', 'inline')
      2 import matplotlib.pyplot as plt
----> 3 housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
      4              s=housing["population"]/100, label="population", figsize=(10,7),
      5              c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True,
      6              sharex=False)
      7 plt.legend()
      8 save_fig("housing_prices_scatterplot")

File ~/my_env/lib/python3.9/site-packages/pandas/plotting/_core.py:945, in PlotAccessor.__call__(self, *args, **kwargs)
    943 if kind in self._dataframe_kinds:
    944     if isinstance(data, ABCDataFrame):
--> 945         return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs)
    946     else:
    947         raise ValueError(f"plot kind {kind} can only be used for data frames")

File ~/my_env/lib/python3.9/site-packages/pandas/plotting/_matplotlib/__init__.py:71, in plot(data, kind, **kwargs)
     69         kwargs["ax"] = getattr(ax, "left_ax", ax)
     70 plot_obj = PLOT_CLASSES[kind](data, **kwargs)
---> 71 plot_obj.generate()
     72 plot_obj.draw()
     73 return plot_obj.result

File ~/my_env/lib/python3.9/site-packages/pandas/plotting/_matplotlib/core.py:452, in MPLPlot.generate(self)
    450 self._compute_plot_data()
    451 self._setup_subplots()
--> 452 self._make_plot()
    453 self._add_table()
    454 self._make_legend()

File ~/my_env/lib/python3.9/site-packages/pandas/plotting/_matplotlib/core.py:1225, in ScatterPlot._make_plot(self)
   1223 if self.colormap is not None:
   1224     if mpl_ge_3_6_0():
-> 1225         cmap = mpl.colormaps[self.colormap]
   1226     else:
   1227         cmap = self.plt.cm.get_cmap(self.colormap)

File ~/my_env/lib/python3.9/site-packages/matplotlib/cm.py:87, in ColormapRegistry.__getitem__(self, item)
     85 def __getitem__(self, item):
     86     try:
---> 87         return self._cmaps[item].copy()
     88     except KeyError:
     89         raise KeyError(f"{item!r} is not a known colormap name") from None

TypeError: unhashable type: 'LinearSegmentedColormap'

我只想将 matplotlib 用于简单且正常的图形,但我找不到问题所在。

【问题讨论】:

  • 显然 .plot() 方法需要一个颜色图姓名而不是颜色图实例

标签: matplotlib data-science jupyter


【解决方案1】:

不要传入cmap=plt.get_cmap("jet"),只需传入"jet"

所以电话应该是

%matplotlib inline  
import matplotlib.pyplot as plt
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
             s=housing["population"]/100, label="population", figsize=(10,7),
             c="median_house_value", cmap="jet", colorbar=True,
             sharex=False)
plt.legend()
save_fig("housing_prices_scatterplot")

【讨论】:

  • 还不行。这是值错误:ValueError:'c' 参数必须是颜色、颜色序列或数字序列,而不是 median_house_value
  • 您使用的是什么版本的 python、matplotlib 和 pandas?使用 python 3.10(本书建议使用 3.8)、pandas 1.5.1、matplotlib 3.6.1,一切都按预期工作
  • 我正在阅读与 OP 相同的书,确实传递字符串完全有效。我猜 matplotlib 在最近的一些版本中更改了这里的 API?
【解决方案2】:

在我删除这个之后,绘制了一个没有错误的图:cmap=plt.get_camp("jet")。颜色范围是默认的,不是从蓝色到红色。

【讨论】:

  • 使用名为 Carnets plus 的应用程序在我的 ipad 上尝试了原始代码,它工作得很好。所以这个错误很可能是因为我使用 Windows。不确定您是否也在使用 Windows。
【解决方案3】:

使用 colormap 参数而不是 cmap 并传入颜色图名称:

%matplotlib inline
import matplotlib.pyplot as plt
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
             s=housing["population"]/100, label="population", figsize=(10,7),
             c="median_house_value", colormap="jet", colorbar=True,
             sharex=False)
plt.legend()
save_fig("housing_prices_scatterplot")

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2018-08-05
    • 2014-07-24
    • 2015-07-07
    相关资源
    最近更新 更多