尝试运行此代码时出现键错误0:
# Draw Plot
plt.figure(figsize=(13,10), dpi= 80)
sns.boxplot(x='demand', y='Price', data=df, notch=False)
# Add N Obs inside boxplot (optional)
def add_n_obs(df,group_col,y):
medians_dict = {grp[0]:grp[1][y].median() for grp in df.groupby(group_col)}
xticklabels = [x.get_text() for x in plt.gca().get_xticklabels()]
n_obs = df.groupby(group_col)[y].size().values
for (x, xticklabel), n_ob in zip(enumerate(xticklabels), n_obs):
plt.text(x, medians_dict[xticklabel]*1.01, "#obs : "+str(n_ob), horizontalalignment='center', fontdict={'size':14}, color='white')
add_n_obs(df,group_col='demand',y='Price')
# Decoration
plt.title('Box Plot', fontsize=22)
plt.ylim(10, 40)
plt.show()
答案 0 :(得分:0)
我尝试使用seaborn提供的默认提示数据运行代码:
from matplotlib import pyplot as plt
import seaborn as sns
df = sns.load_dataset("tips")
# Draw Plot
plt.figure(figsize=(13,10), dpi= 80)
sns.boxplot(x="day", y="total_bill", data=df, notch=False)
# Add N Obs inside boxplot (optional)
def add_n_obs(df,group_col,y):
medians_dict = {grp[0]:grp[1][y].median() for grp in df.groupby(group_col)}
xticklabels = [x.get_text() for x in plt.gca().get_xticklabels()]
n_obs = df.groupby(group_col)[y].size().values
for (x, xticklabel), n_ob in zip(enumerate(xticklabels), n_obs):
plt.text(x, medians_dict[xticklabel]*1.01, "#obs : "+str(n_ob), horizontalalignment='center', fontdict={'size':14}, color='white')
add_n_obs(df,group_col='day',y='total_bill')
# Decoration
plt.title('Box Plot', fontsize=22)
plt.ylim(10, 40)
plt.show()
,似乎工作正常。您确定数据框变量df确实具有键“需求”和“价格”吗?