Oli*_*r G 35 python matplotlib legend seaborn
在Python中使用数据框和此代码,我能够创建一个图:
g = sns.lmplot('credibility', 'percentWatched', data=data, hue = 'millennial', markers = ["+", "."], x_jitter = True, y_jitter = True, size=5)
g.set(xlabel = 'Credibility Ranking\n ? Low High ?', ylabel = 'Percent of Video Watched [%]')
Run Code Online (Sandbox Code Playgroud)
但是有传说说"+ 0"和".1"对读者来说并不是很有帮助.如何编辑图例的标签?理想情况下,它不是说"千禧一代",而是说"一代"和"+千禧一代"."老一代"
Ser*_*ity 38
如果legend_out
设置为,True
那么图例是可用的思想g._legend
属性,它是图形的一部分.Seaborn图例是标准的matplotlib图例对象.因此,您可以更改图例文字:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = True)
# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)
sns.plt.show()
Run Code Online (Sandbox Code Playgroud)
如果legend_out
设置为另一种情况False
.您必须定义哪些轴具有图例(在下面的示例中,这是轴编号0):
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = False)
# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()
Run Code Online (Sandbox Code Playgroud)
此外,您可以结合两种情况并使用此代码:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = True)
# check axes and find which is have legend
for ax in g.axes.flat:
leg = g.axes.flat[0].get_legend()
if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend
# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()
Run Code Online (Sandbox Code Playgroud)
此代码适用于基于Grid
类的任何seaborn图.
Gle*_*son 27
花了我一段时间阅读以上内容。这是我的答案:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=False
)
plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)
Run Code Online (Sandbox Code Playgroud)
请参考此以获取更多参数:matplotlib.pyplot.legend
归档时间: |
|
查看次数: |
53978 次 |
最近记录: |