gpt4 book ai didi

pandas - 为什么 set_titles 不生成标题(Seaborn 和 Factorplot)?

转载 作者:行者123 更新时间:2023-12-05 07:47:04 26 4
gpt4 key购买 nike

这是我正在使用的代码。这是一个可以复制和粘贴的独立代码。

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



### Load the Titanic dataset
titanic = sns.load_dataset("titanic")

### Divide the data by sex; male and female

male = titanic[titanic.sex == 'male']
female = titanic[titanic.sex == 'female']




### Now use groupby to group by fare//5 and then create a column with the survival rate for each group

male_chart= male.groupby([male.fare // 5]).survived.mean().reset_index()
female_chart= female.groupby([female.fare // 5]).survived.mean().reset_index()



#Plot male_chart
sns.set(style="whitegrid")
g = sns.factorplot(x='fare', y= 'survived', data=male_chart,
size=6, aspect =3 ,kind="bar", palette="muted")

g.despine(left=True)
g.set_ylabels("Survival Probability")
g.set_xlabels('Fare *5')
g.set_titles('Males') # set_title doesn't produce "Males" on the chart itself



#sns.plt.title('Males') #This code seems to work but not sure why it does.


#plot: female_chart

h= sns.factorplot(x='fare', y= 'survived', data=female_chart,
size=6, aspect =3 ,kind="bar", palette="muted")
h.despine(left=True)
h.set_ylabels("survival probability")
h.set_xlabels('fare *5')
h.set_titles('Females') #Once again doesn't work.
#sns.plt.title('Females') #but this works
plt.show()

我在运行“set_titles”行时没有收到任何错误,但它没有在图表本身上生成标题。我如何错误地使用 set_title?感谢你的帮助。

最佳答案

set_titles ("NName of plot") 仅适用于 FacetGrid,其中有 x 列或 y 行。

(例如)

facet_grid = sns.relplot(data=data, x = "X", y = "Y", col = "Split"). set_titles("Works fine")
如果您的图不是FacetGrid 并且您使用set_titles 它不会显示标题

例如

不会起作用

plt.figure(figsize=(20,6))  
sns.displot(df["GPA"],kind='kde').set_titles("Distribution of Data")

工作正常

plt.figure(figsize=(20,6)) # works fine
sns.displot(df["GPA"],kind='kde').set(title='Title of Plot')

https://seaborn.pydata.org/generated/seaborn.FacetGrid.set_titles.html

关于pandas - 为什么 set_titles 不生成标题(Seaborn 和 Factorplot)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40113860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com