Python 如何使用plt可视化多个条形图。根据axis的索引,axis必须迭代所有视觉效果?
我试图年复一年地描绘每个国家的预期寿命,我写了一个运行良好的代码Python 如何使用plt可视化多个条形图。根据axis的索引,axis必须迭代所有视觉效果?,python,pandas,data-science,data-visualization,Python,Pandas,Data Science,Data Visualization,我试图年复一年地描绘每个国家的预期寿命,我写了一个运行良好的代码 #Lets Create a Function that will create a relation between Year,life Expectancy with respect to different country def EDA_features(country,life_expectancy,data): for i in set(data[country]): plt.bar(ra
#Lets Create a Function that will create a relation between Year,life Expectancy with respect to different country
def EDA_features(country,life_expectancy,data):
for i in set(data[country]):
plt.bar(range(len(set(data[country]))),data[data[country]==i][life_expectancy])
plt.xticks(range(len(set(data.Year))),labels=list(set(data.Year)))
plt.xlabel('Year')
plt.ylabel(f'{life_expectancy}')
plt.title(f"Year vs {life_expectancy} for {i}")
plt.show()
我想使用plt.subplot将此可视化显示为3或2行
我试过这个密码
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True, figsize=(10,5))
for ax,country in zip(list(set(df.Country)),[ax1,ax2,ax3,ax4,ax5,ax6]):
sns.barplot(range(len(set(df.Year))),df[df.Country==country]['Life expectancy at birth (years)'],ax=ax)
ax.set_xticks(range(len(set(data.Year))))
ax.set_xticklabels(list(set(data.Year)))
plt.xlabel('Year')
plt.ylabel('Life expectancy at birth (years)')
plt.title(f"Year vs Life expectancy at birth (years) for {country}")
plt.show()
它抛出以下错误AttributeError:“bool”对象没有属性“all”
有人能帮我吗?你的拉链顺序不对: 数字排在第二位,而国家排在第一位。请注意,在for语句开头创建
ax,country
元组时,ax将包含country,country将包含子批
for ax,country in zip(list(set(df.Country)),[ax1,ax2,ax3,ax4,ax5,ax6]):
像这样交换:
for country, ax in zip(list(set(df.Country)),[ax1,ax2,ax3,ax4,ax5,ax6]):
df = pd.DataFrame({'Country':np.repeat(["A","B","C","D","E","F"],5),
'Life expectancy at birth (years)':np.random.uniform(50,80,30),
'Year':np.tile([2000,2001,2002,2003,2004],6)})
假设您的数据帧如下所示:
for country, ax in zip(list(set(df.Country)),[ax1,ax2,ax3,ax4,ax5,ax6]):
df = pd.DataFrame({'Country':np.repeat(["A","B","C","D","E","F"],5),
'Life expectancy at birth (years)':np.random.uniform(50,80,30),
'Year':np.tile([2000,2001,2002,2003,2004],6)})
您可以简单地使用,使用col\u wrap
指定列数:
sns.catplot(x="Year",y="Life expectancy at birth (years)",
col="Country",col_wrap=3,data=df,kind="bar",height=3)
或者简化上面的子批次代码也会得到类似的结果:
fig,axs = plt.subplots(2,3, sharex=True, sharey=True, figsize=(10,5))
axs = axs.flatten()
Years = df.Year.unique()
Countries = df.Country.unique()
for i,cty in enumerate(Countries):
sns.barplot(x = "Year", y = "Life expectancy at birth (years)",
data = df[df.Country==cty],ax=axs[i])
axs[i].set_xticks(range(len(Years)))
axs[i].set_xticklabels(Years)
plt.xlabel('Year')
plt.ylabel('Life expectancy at birth (years)')