首页 > 解决方案 > 在python中设置多个xlabels

问题描述

我正在用一些数据生成 5 个图。它们都应该具有相同的 ylabel,但在 x_axis 列表中给出了不同的 xlabel。例如,第一个散点图应该有 xlabel“A”等等。

我该如何管理?谢谢你

def test(x):
 x_axis = ["A", "B", "C", "D", "E"]

 #DATA
 x = df[x_axis[x]]
 y = df["Return +1M"]
 y2 = df["Return +3M"]
 y3 = df["Return +6M"]

 colors = ['b', 'r', 'g']

 #SCATTER PLOT 
 return_1m = plt.scatter(x,y, marker="x", color=colors[0])
 return_3m = plt.scatter(x,y2, marker="x", color=colors[1])
 return_6m = plt.scatter(x,y3, marker="x", color=colors[2])

 plt.legend((return_1m, return_3m, return_6m),
           ('Return +1M', 'Return +3M', 'Return +6M'),
           scatterpoints=1,
           loc='lower right',
           ncol=1,
           fontsize=8)

 plt.ylabel("Return")
 plt.show()

for i in [0,1,2,3,4]:
 test(i) 

标签: pythonmatplotlib

解决方案


fig, (ax1, ax2,ax3,ax4,ax5) = plt.subplots(1,5)

# Whatever you want your values to be:-
ax1.plot([1,2,3,4,5], [1,2,3,4,10], 'go')
ax2.plot([1,2,3,4,5], [2,3,4,5,11], 'b*') 


#X labels:-

ax1.set_xlabel('whatever you want')  
ax2.set_xlabel('whatever you want')
ax3.set_xlabel('whatever you want')
ax4.set_xlabel('whatever you want')
ax5.set_xlabel('whatever you want')
#You can do same with Y axis

您还可以使用循环来设置 xlabel。这样你就不需要一次又一次地写同一行


推荐阅读