2016-02-21 32 views
14

Một trong những điều thú vị nhất mà bạn có thể dễ dàng thực hiện trong seabornboxplot + stripplot kết hợp:sanh ở biển boxplot + stripplot: lặp lại huyền thoại

import matplotlib.pyplot as plt 
import seaborn as sns 
import pandas as pd 

tips = sns.load_dataset("tips") 

sns.stripplot(x="day", y="total_bill", hue="smoker", 
data=tips, jitter=True, 
palette="Set2", split=True,linewidth=1,edgecolor='gray') 

sns.boxplot(x="day", y="total_bill", hue="smoker", 
data=tips,palette="Set2",fliersize=0) 

plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.); 

boxplot+stripplot

Thật không may, như bạn thấy ở trên, nó được sản xuất tăng gấp đôi huyền thoại, một cho boxplot, một cho stripplot. Rõ ràng, nó trông vô lý và dư thừa. Nhưng tôi dường như không thể tìm ra cách để loại bỏ huyền thoại stripplot và chỉ để lại chú thích boxplot. Có lẽ, tôi bằng cách nào đó có thể xóa các mục từ plt.legend, nhưng tôi không thể tìm thấy nó trong tài liệu.

Trả lời

18

Bạn có thể get what handles/labels should exist trong chú giải trước khi thực sự vẽ chính chú thích đó. Sau đó, bạn chỉ vẽ chú thích với chú thích cụ thể mà bạn muốn.

import matplotlib.pyplot as plt 
import seaborn as sns 
import pandas as pd 

tips = sns.load_dataset("tips") 

sns.stripplot(x="day", y="total_bill", hue="smoker", 
data=tips, jitter=True, 
palette="Set2", split=True,linewidth=1,edgecolor='gray') 

# Get the ax object to use later. 
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", 
data=tips,palette="Set2",fliersize=0) 

# Get the handles and labels. For this example it'll be 2 tuples 
# of length 4 each. 
handles, labels = ax.get_legend_handles_labels() 

# When creating the legend, only use the first two elements 
# to effectively remove the last two. 
l = plt.legend(handles[0:2], labels[0:2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) 

example plot

+0

Awesome! Cảm ơn, người đàn ông! –

1

tôi muốn thêm rằng nếu bạn sử dụng ô phụ, việc xử lý huyền thoại có thể có vấn đề hơn một chút. Đoạn mã trên, mang lại một con số rất đẹp bằng cách này (@Sergey Antopolskiy và @Ffisegydd), sẽ không định vị lại huyền thoại trong một subplot, nó sẽ xuất hiện rất bướng bỉnh. Xem mã trên phù hợp với subplots:

import matplotlib.pyplot as plt 
import seaborn as sns 
import pandas as pd 

tips = sns.load_dataset("tips") 

fig, axes = sns.plt.subplots(2,2) 

sns.stripplot(x="day", y="total_bill", hue="smoker", 
       data=tips, jitter=True, palette="Set2", 
       split=True,linewidth=1,edgecolor='gray', ax = axes[0,0]) 

ax = sns.boxplot(x="day", y="total_bill", hue="smoker", 
       data=tips,palette="Set2",fliersize=0, ax = axes[0,0]) 

handles, labels = ax.get_legend_handles_labels() 

l = plt.legend(handles[0:2], labels[0:2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) 

duplicated legend

Truyền thuyết ban đầu vẫn còn. Để xóa nó, bạn có thể thêm dòng này:

axes[0,0].legend(handles[:0], labels[:0]) 

corrected legend

Các vấn đề liên quan