How to display x axis label for each matplotlib subplot

点点圈 提交于 2019-12-11 04:35:57

问题


I want to add an x axis label below each subplot. I use this code to create the charts:

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()

This is how it looks. Only the first one shows

How can I show a different x axis label under each subplot?


回答1:


You are using ax.set_xlabel wrong, which is a function (first call is correct, the others are not):

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()



回答2:


You can add a title above each plot using:

ax.set_title('your title')



回答3:


That's easy, just use matplotlib.axes.Axes.set_title, here's a little example out of your code:

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()


来源:https://stackoverflow.com/questions/39257712/how-to-display-x-axis-label-for-each-matplotlib-subplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!