«KeyError: ('f', None)" при попытке построить легенду с некоторыми точками - PullRequest
0 голосов
/ 29 марта 2019

Я пытаюсь нарисовать две отдельные точки на гексбиновом графике с помощью цветов, маркеров и меток. Когда я пытаюсь включить легенду, я получаю KeyError. Обратите внимание, что я делаю то же самое с двумя разными наборами данных, и он отлично работает с одним набором и не работает с другим.

Сначала я попытался использовать plt.plot, затем с plt.scatter. Я пытался использовать разные цвета. Я попытался явно указать цвет и маркер. Я не могу найти в Интернете ничего, что описывает ту же проблему.

fig=plt.figure(figsize=(10,7))
plt.hexbin(x,y)
plt.colorbar()
plt.scatter(x1,y1,c='w',marker='*',label='Field 1')
plt.scatter(x2,y2,c='w',marker='^',label='Field 2')
plt.legend(loc='lower right')
plt.show()

Что касается других моих данных, то это прекрасно. Но здесь я получаю сообщение об ошибке:

KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    165     try:
--> 166         rgba = _colors_full_map.cache[c, alpha]
    167     except (KeyError, TypeError):  # Not in cache, or unhashable.

KeyError: ('f', None)

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-33-69334a5c3996> in <module>()
     21 plt.scatter(zb,np.log(massb),c='w',marker='*',label='Field 1')
     22 plt.scatter(za,np.log(massa),c='w',marker='^',label='Field 2')
---> 23 plt.legend(loc='lower right')
     24 #plt.title('Stellar mass vs sSFR')
     25 plt.show()

~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in legend(*args, **kwargs)
   3821 @docstring.copy_dedent(Axes.legend)
   3822 def legend(*args, **kwargs):
-> 3823     ret = gca().legend(*args, **kwargs)
   3824     return ret
   3825 

~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in legend(self, *args, **kwargs)
    555         if len(extra_args):
    556             raise TypeError('legend only accepts two non-keyword arguments')
--> 557         self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
    558         self.legend_._remove_method = lambda h: setattr(self, 'legend_', None)
    559         return self.legend_

~\Anaconda3\lib\site-packages\matplotlib\legend.py in __init__(self, parent, handles, labels, loc, numpoints, markerscale, markerfirst, scatterpoints, scatteryoffsets, prop, fontsize, borderpad, labelspacing, handlelength, handleheight, handletextpad, borderaxespad, columnspacing, ncol, mode, fancybox, shadow, title, framealpha, edgecolor, facecolor, bbox_to_anchor, bbox_transform, frameon, handler_map)
    697 
    698         # init with null renderer
--> 699         self._init_legend_box(handles, labels, markerfirst)
    700 
    701         # If shadow is activated use framealpha if not

~\Anaconda3\lib\site-packages\matplotlib\legend.py in _init_legend_box(self, handles, labels, markerfirst)
    952                 # original artist/handle.
    953                 handle_list.append(handler.legend_artist(self, orig_handle,
--> 954                                                          fontsize, handlebox))
    955                 handles_and_labels.append((handlebox, textbox))
    956 

~\Anaconda3\lib\site-packages\matplotlib\legend_handler.py in legend_artist(self, legend, orig_handle, fontsize, handlebox)
    117         artists = self.create_artists(legend, orig_handle,
    118                                       xdescent, ydescent, width, height,
--> 119                                       fontsize, handlebox.get_transform())
    120 
    121         # create_artists will return a list of artists.

~\Anaconda3\lib\site-packages\matplotlib\legend_handler.py in create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
    726         p = Rectangle(xy=(-xdescent, -ydescent),
    727                       width=width, height=height)
--> 728         self.update_prop(p, orig_handle, legend)
    729         p.set_transform(trans)
    730         return [p]

~\Anaconda3\lib\site-packages\matplotlib\legend_handler.py in update_prop(self, legend_handle, orig_handle, legend)
     74     def update_prop(self, legend_handle, orig_handle, legend):
     75 
---> 76         self._update_prop(legend_handle, orig_handle)
     77 
     78         legend._set_artist_props(legend_handle)

~\Anaconda3\lib\site-packages\matplotlib\legend_handler.py in _update_prop(self, legend_handle, orig_handle)
    710         edgecolor = getattr(orig_handle, '_original_edgecolor',
    711                             orig_handle.get_edgecolor())
--> 712         legend_handle.set_edgecolor(first_color(edgecolor))
    713         facecolor = getattr(orig_handle, '_original_facecolor',
    714                             orig_handle.get_facecolor())

~\Anaconda3\lib\site-packages\matplotlib\legend_handler.py in first_color(colors)
    697             if colors is None:
    698                 return None
--> 699             colors = mcolors.to_rgba_array(colors)
    700             if len(colors):
    701                 return colors[0]

~\Anaconda3\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    265     result = np.empty((len(c), 4), float)
    266     for i, cc in enumerate(c):
--> 267         result[i] = to_rgba(cc, alpha)
    268     return result
    269 

~\Anaconda3\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    166         rgba = _colors_full_map.cache[c, alpha]
    167     except (KeyError, TypeError):  # Not in cache, or unhashable.
--> 168         rgba = _to_rgba_no_colorcycle(c, alpha)
    169         try:
    170             _colors_full_map.cache[c, alpha] = rgba

~\Anaconda3\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    210         except ValueError:
    211             pass
--> 212         raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
    213     # tuple color.
    214     c = np.array(c)

ValueError: Invalid RGBA argument: 'f'

Я понятия не имею, что такое "f" и откуда оно. Я не понимаю, почему не работает использование основных цветов matplotlib.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...