我想在每个子图下面添加一个x轴标签。我使用此代码创建图表:
fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(1,3,1)
ax1.set_xlim([min(df1["Age"]),max(df1["Age"])])
ax1.set_xlabel("All Age Freq")
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1,3,2)
ax2.set_xlim([min(df2["Age"]),max(df2["Age"])])
ax2.set_xlabel = "Survived by Age Freq"
ax2 = df2["Age"].hist(color="seagreen")
ax3 = fig.add_subplot(1,3,3)
ax3.set_xlim([min(df3["Age"]),max(df3["Age"])])
ax3.set_xlabel = "Not Survived by Age Freq"
ax3 = df3["Age"].hist(color="cadetblue")
plt.show()
这就是它的样子。只有第一个显示
如何在每个subplot
下显示不同的x轴标签?
答案 0 :(得分:3)
您使用ax.set_xlabel
错误,这是功能(第一次通话是正确的,其他则不是):
fig = plt.figure(figsize=(16,8))
ax1 = fig.add_subplot(1,3,1)
ax1.set_xlim([min(df1["Age"]),max(df1["Age"])])
ax1.set_xlabel("All Age Freq") # CORRECT USAGE
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1,3,2)
ax2.set_xlim([min(df2["Age"]),max(df2["Age"])])
ax2.set_xlabel = "Survived by Age Freq" # ERROR set_xlabel is a function
ax2 = df2["Age"].hist(color="seagreen")
ax3 = fig.add_subplot(1,3,3)
ax3.set_xlim([min(df3["Age"]),max(df3["Age"])])
ax3.set_xlabel = "Not Survived by Age Freq" # ERROR set_xlabel is a function
ax3 = df3["Age"].hist(color="cadetblue")
plt.show()
答案 1 :(得分:0)
您可以使用以下方法在每个地块上方添加标题:
ax.set_title('your title')
答案 2 :(得分:0)
这很简单,只需使用matplotlib.axes.Axes.set_title,这里有一些代码示例:
from matplotlib import pyplot as plt
import pandas as pd
df1 = pd.DataFrame({
"Age":[1,2,3,4]
})
df2 = pd.DataFrame({
"Age":[10,20,30,40]
})
df3 = pd.DataFrame({
"Age":[100,200,300,400]
})
fig = plt.figure(figsize=(16, 8))
ax1 = fig.add_subplot(1, 3, 1)
ax1.set_title("Title for df1")
ax1.set_xlim([min(df1["Age"]), max(df1["Age"])])
ax1.set_xlabel("All Age Freq")
ax1 = df1["Age"].hist(color="cornflowerblue")
ax2 = fig.add_subplot(1, 3, 2)
ax2.set_xlim([min(df2["Age"]), max(df2["Age"])])
ax2.set_title("Title for df2")
ax2.set_xlabel = "Survived by Age Freq"
ax2 = df2["Age"].hist(color="seagreen")
ax3 = fig.add_subplot(1, 3, 3)
ax3.set_xlim([min(df3["Age"]), max(df3["Age"])])
ax3.set_title("Title for df3")
ax3.set_xlabel = "Not Survived by Age Freq"
ax3 = df3["Age"].hist(color="cadetblue")
plt.show()