2015-05-27 24 views
8

Vorrei creare un grafico delle serie temporali utilizzando seaborn.tsplot come in this example from tsplot documentation, ma con la legenda spostata a destra, all'esterno della figura.Spostare la legenda fuori figura in seaborn tsplot

example

Sulla base delle linee 339-340 in seaborn's timeseries.py, sembra che seaborn.tsplot attualmente non consente il controllo diretto di posizionamento leggenda:

if legend: 
     ax.legend(loc=0, title=legend_name) 

C'è una soluzione matplotlib? Sto usando seaborn 0.6-dev.

+2

Penso che se si chiama 'ax.legend' nuovamente lo si ridisegna, non ne aggiunge un secondo. – mwaskom

+0

@mwaskom: funziona per me. Grazie! – bnelsj

risposta

20

Infatti, seaborn non gestisce bene le leggende finora. È possibile utilizzare plt.legend() per controllare le proprietà delle legende direttamente tramite matplotlib, in conformità con Matplotlib Legend Guide.

Esempio:

import matpltlib.pyplot as plt 
import seaborn as sns 
sns.set(style="darkgrid") 

# Load the long-form example gammas dataset 
gammas = sns.load_dataset("gammas") 

# Plot the response with standard error 
sns.tsplot(data=gammas, time="timepoint", unit="subject", 
      condition="ROI", value="BOLD signal") 

# Put the legend out of the figure 
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) 

Modified legend position

+0

La linea finale è la soluzione. Ha funzionato anche per il mio barplot. – Denziloe

0

La risposta da Sergey ha lavorato molto per me utilizzando un seaborn.tsplot ma non ero in grado di farlo funzionare per un seaborn.lmplot così ho guardato un po 'più profondo e trovato un altro soluzione:

Esempio:

import seaborn as sns 
import pandas as pd 

# load data 
df = pd.DataFrame.from_csv('mydata.csv') 

# create with hue but without legend 
g = sns.lmplot(x="x_data", y="y_data", hue="condition", legend=False, data=df) 

# resize figure box to -> put the legend out of the figure 
box = g.ax.get_position() # get position of figure 
g.ax.set_position([box.x0, box.y0, box.width * 0.85, box.height]) # resize position 

# Put a legend to the right side 
g.ax.legend(loc='center right', bbox_to_anchor=(1.25, 0.5), ncol=1) 

sns.plt.show(g) 

Forse devi giocare con i valori per adattarli alla tua leggenda. This risposta sarà anche utile se avete bisogno di più esempi.

Problemi correlati