Bio Bio - 3 months ago 51
Python Question

add a label to a plot with seaborn

I did a plot using seaborn,
Here is my pltt enter image description here
I would like to add a label for each line.
Can you help me please?

import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates
from matplotlib import style
import pandas as pd
%pylab inline
import seaborn as sns
sns.set_style('darkgrid')
import io
style.use('ggplot')
from datetime import datetime
import time
fig = plt.figure(figsize=(12, 8), dpi=100)
ax1 = fig.add_subplot(111)
x1 = pd.to_datetime(df_no_missing.TIMESTAMP, format="%h:%m")
y1 = df_no_missing.P_ACT_KW
y3 = df_no_missing.P_SOUSCR
yearFmt = mdates.DateFormatter("%H:%M:%S")
ax1.xaxis.set_major_formatter(yearFmt)
ax2 = ax1.twinx()

ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
ax1.plot(x, y3, 'r-')
ax1.set_xlabel('temps')
ax1.set_ylabel('puissance', color='g')
ax2.set_ylabel('dépassement', color='b')
plt.ylim(plt.ylim()[0], 1.0)
plt.show()


Thank you in advance
EDIT

I try like you mention :

fig = plt.figure(figsize=(12, 5), dpi=100)
ax1 = fig.add_subplot(111)
x1 = pd.to_datetime(df_no_missing.TIMESTAMP, format="%h:%m")
y1 = df_no_missing.P_ACT_KW
y3 = df_no_missing.P_SOUSCR
yearFmt = mdates.DateFormatter("%H:%M:%S")
ax1.xaxis.set_major_formatter(yearFmt)
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-', label='label 1')
ax2.plot(x, y2, 'b-', label='label 2')
ax1.plot(x, y3, 'r-', label='label 3')
ax1.plot(0, 0, 'b-', label='label 2')
ax.legend(loc=0) # add legend in top right corner
ax.grid() # show grid lines
ax1.set_xlabel('temps')
ax1.set_ylabel('puissance', color='g')
ax2.set_ylabel('dépassement', color='b')
plt.ylim(plt.ylim()[0], 1.0)
plt.show()


But I got this error :


---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
C:\Users\Demonstrator\Anaconda3\lib\site-packages\IPython\core\formatters.py


in call(self, obj)
337 pass
338 else:
--> 339 return printer(obj)
340 # Finally look for special method names
341 method = _safe_get_formatter_method(obj, self.print_method)

C:\Users\Demonstrator\Anaconda3\lib\site-packages\IPython\core\pylabtools.py


in (fig)
226
227 if 'png' in formats:
--> 228 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
229 if 'retina' in formats or 'png2x' in formats:
230 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

C:\Users\Demonstrator\Anaconda3\lib\site-packages\IPython\core\pylabtools.py


in print_figure(fig, fmt, bbox_inches, **kwargs)
117
118 bytes_io = BytesIO()
--> 119 fig.canvas.print_figure(bytes_io, **kw)
120 data = bytes_io.getvalue()
121 if fmt == 'svg':

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\backend_bases.py


in print_figure(self, filename, dpi, facecolor, edgecolor,
orientation, format, **kwargs)
2178 orientation=orientation,
2179 dryrun=True,
-> 2180 **kwargs)
2181 renderer = self.figure._cachedRenderer
2182 bbox_inches = self.figure.get_tightbbox(renderer)

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py


in print_png(self, filename_or_obj, *args, **kwargs)
525
526 def print_png(self, filename_or_obj, *args, **kwargs):
--> 527 FigureCanvasAgg.draw(self)
528 renderer = self.get_renderer()
529 original_dpi = renderer.dpi

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py


in draw(self)
472
473 try:
--> 474 self.figure.draw(self.renderer)
475 finally:
476 RendererAgg.lock.release()

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\artist.py


in draw_wrapper(artist, renderer, *args, **kwargs)
59 def draw_wrapper(artist, renderer, *args, **kwargs):
60 before(artist, renderer)
---> 61 draw(artist, renderer, *args, **kwargs)
62 after(artist, renderer)
63

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\figure.py


in draw(self, renderer)
1157 dsu.sort(key=itemgetter(0))
1158 for zorder, a, func, args in dsu:
-> 1159 func(*args)
1160
1161 renderer.close_group('figure')

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\artist.py


in draw_wrapper(artist, renderer, *args, **kwargs)
59 def draw_wrapper(artist, renderer, *args, **kwargs):
60 before(artist, renderer)
---> 61 draw(artist, renderer, *args, **kwargs)
62 after(artist, renderer)
63

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\axes\_base.py


in draw(self, renderer, inframe)
2322
2323 for zorder, a in dsu:
-> 2324 a.draw(renderer)
2325
2326 renderer.close_group('axes')

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\artist.py


in draw_wrapper(artist, renderer, *args, **kwargs)
59 def draw_wrapper(artist, renderer, *args, **kwargs):
60 before(artist, renderer)
---> 61 draw(artist, renderer, *args, **kwargs)
62 after(artist, renderer)
63

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\axis.py


in draw(self, renderer, *args, **kwargs)
1104 renderer.open_group(name)
1105
-> 1106 ticks_to_draw = self._update_ticks(renderer)
1107 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
1108 renderer)

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\axis.py


in _update_ticks(self, renderer)
947
948 interval = self.get_view_interval()
--> 949 tick_tups = [t for t in self.iter_ticks()]
950 if self._smart_bounds:
951 # handle inverted limits

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\axis.py


in (.0)
947
948 interval = self.get_view_interval()
--> 949 tick_tups = [t for t in self.iter_ticks()]
950 if self._smart_bounds:
951 # handle inverted limits

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\axis.py


in iter_ticks(self)
890 Iterate through all of the major and minor ticks.
891 """
--> 892 majorLocs = self.major.locator()
893 majorTicks = self.get_major_ticks(len(majorLocs))
894 self.major.formatter.set_locs(majorLocs)

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\dates.py


in call(self)
1004 def call(self):
1005 'Return the locations of the ticks'
-> 1006 self.refresh()
1007 return self._locator()
1008

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\dates.py


in refresh(self)
1024 def refresh(self):
1025 'Refresh internal information based on current limits.'
-> 1026 dmin, dmax = self.viewlim_to_dt()
1027 self._locator = self.get_locator(dmin, dmax)
1028

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\dates.py


in viewlim_to_dt(self)
768 vmin, vmax = vmax, vmin
769
--> 770 return num2date(vmin, self.tz), num2date(vmax, self.tz)
771
772 def _get_unit(self):

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\dates.py


in num2date(x, tz)
417 tz = _get_rc_timezone()
418 if not cbook.iterable(x):
--> 419 return _from_ordinalf(x, tz)
420 else:
421 x = np.asarray(x)

C:\Users\Demonstrator\Anaconda3\lib\site-packages\matplotlib\dates.py


in _from_ordinalf(x, tz)
269
270 ix = int(x)
--> 271 dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
272
273 remainder = float(x) - ix

ValueError: ordinal must be >= 1





<matplotlib.figure.Figure at 0x1d3b041a400>



print (df_no_missing.head())



TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR SITE \
145 2015-08-01 23:10:00 248.0 HC 425.0 ST GEREON
146 2015-08-01 23:20:00 244.0 HC 425.0 ST GEREON
147 2015-08-01 23:30:00 243.0 HC 425.0 ST GEREON
148 2015-08-01 23:40:00 238.0 HC 425.0 ST GEREON
149 2015-08-01 23:50:00 234.0 HC 425.0 ST GEREON

TARIF depassement date time
145 TURPE_HTA5 0.0 2015-08-01 23:10:00
146 TURPE_HTA5 0.0 2015-08-01 23:20:00
147 TURPE_HTA5 0.0 2015-08-01 23:30:00
148 TURPE_HTA5 0.0 2015-08-01 23:40:00
149 TURPE_HTA5 0.0 2015-08-01 23:50:00


Answer

You can specify the label names to each subplot axis and use plt.legend to add the appropriate legends to the center right corner.

fig = sns.plt.figure(figsize=(12, 5), dpi=100)
ax1 = fig.add_subplot(111)
x1 = pd.to_datetime(df_no_missing.TIMESTAMP)
y1 = df_no_missing.P_ACT_KW
y2 = df_no_missing.depassement
y3 = df_no_missing.P_SOUSCR
yearFmt = mdates.DateFormatter("%H:%M:%S")
ax1.xaxis.set_major_formatter(yearFmt)
ax1.plot(x1, y1, 'g-', label='p_act_kw')
ax1.plot(x1, y3, 'r-', label='p_souscr')
ax2 = ax1.twinx()
ax2.plot(x1, y2, 'b-', label='depassement')
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, loc='center right')
ax1.set_xlabel('temps')
ax1.set_ylabel('puissance', color='g')
ax2.set_ylabel('dépassement', color='b')
sns.plt.ylim(plt.ylim()[0], 1.0)
sns.plt.show()

Image

Comments