将图例添加到Matplotlib散点图

时间:2019-02-10 12:03:17

标签: python pandas matplotlib legend pixel

我正在按照Randy Olson的方法制作漂亮的时间趋势图(请参见here)。

当我绘制以下代码时:

tableau20 = [(31, 119, 180), (174, 199, 232)]  
for i in range(len(tableau20)):    
    r, g, b = tableau20[i]    
    tableau20[i] = (r / 255., g / 255., b / 255.)   

plt.figure(figsize=(12, 14))    

# Remove the plot frame lines. They are unnecessary chartjunk.    
ax = plt.subplot(111)    
ax.spines["top"].set_visible(False)    
ax.spines["bottom"].set_visible(False)    
ax.spines["right"].set_visible(False)    
ax.spines["left"].set_visible(False)    

# Ensure that the axis ticks only show up on the bottom and left of the plot.    
# Ticks on the right and top of the plot are generally unnecessary chartjunk.    
ax.get_xaxis().tick_bottom()    
ax.get_yaxis().tick_left()    

majors = ['Number of findings (total)', 'Business Ethics Findings']

for rank, column in enumerate(majors):    
    plt.plot(monthly_df.argrc__End_Date__c.values, monthly_df[column.replace("\n", " ")].values,    
            lw=2.5, color=tableau20[rank])    
    y_pos = monthly_df[column.replace("\n", " ")].values[-1] - 0.5 
    if column == "Number of findings (total)":    
        y_pos += 0.5    
    elif column == 'Business Ethics Findings':    
        y_pos -= 0.5    
    plt.text(2018.1, y_pos, column, fontsize=12, color=tableau20[rank]) 

我收到此错误:

enter image description here

如果我消除

 plt.text(2016, y_pos, column, fontsize=12, color=tableau20[rank]) 

相反,我正确地在图形上绘制了两条线,但是没有图例。如何显示列名?

编辑

我在此处添加回溯以获取更多信息。我希望这会有所帮助。

C:\Users\filippo.sebastio\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py:107: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  warnings.warn(message, mplDeprecation, stacklevel=1)
---------------------------------------------------------------------------
ValueError                                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 <lambda>(fig)
    239 
    240     if 'png' in formats:
--> 241         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    242     if 'retina' in formats or 'png2x' in formats:
    243         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~\Anaconda3\lib\site-packages\IPython\core\pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    123 
    124     bytes_io = BytesIO()
--> 125     fig.canvas.print_figure(bytes_io, **kw)
    126     data = bytes_io.getvalue()
    127     if fmt == 'svg':

~\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2261                 orientation=orientation,
   2262                 bbox_inches_restore=_bbox_inches_restore,
-> 2263                 **kwargs)
   2264         finally:
   2265             if bbox_inches and restore_bbox:

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    515 
    516     def print_png(self, filename_or_obj, *args, **kwargs):
--> 517         FigureCanvasAgg.draw(self)
    518         renderer = self.get_renderer()
    519         original_dpi = renderer.dpi

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in draw(self)
    427         Draw the figure using the renderer
    428         """
--> 429         self.renderer = self.get_renderer(cleared=True)
    430         # acquire a lock on the shared font cache
    431         RendererAgg.lock.acquire()

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in get_renderer(self, cleared)
    452 
    453         if need_new_renderer:
--> 454             self.renderer = RendererAgg(w, h, self.figure.dpi)
    455             self._lastKey = key
    456         elif cleared:

~\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in __init__(self, width, height, dpi)
     99         self.width = width
    100         self.height = height
--> 101         self._renderer = _RendererAgg(int(width), int(height), dpi)
    102         self._filter_renderers = []
    103 

ValueError: Image size of 312943x821 pixels is too large. It must be less than 2^16 in each direction.

<Figure size 864x1008 with 1 Axes>

0 个答案:

没有答案