# Matplotlib: solves the problem that X axis values are not sorted by array

created at 07-13-2021 views: 241

## Problem Description¶

Just look at the title. Let me show you the picture first. The code and data corresponding to this figure are as follows. It is also the original code found on the Internet. It has been slightly modified according to your own data. It is also the easiest way to make you feel that the use of plt is simply too simple. # line chart
plt.rcParams['font.sans-serif'] = ['SimHei']  # Used to display Chinese labels normally
plt.rcParams['axes.unicode_minus'] = False # Used to display the negative sign normally
x=dfGraph['saleArea']
y1=dfGraph['personCount']
plt.plot(x,y1,label='面积与人数')

plt.xlabel('面积(平方米)')
plt.ylabel('90后人数')
plt.title('面积与人数')
plt.legend()
plt.show()


## solution¶

In the above figure, the problem is that the data order of the X axis is not correct. The reason is that plt reorders the data in the order when displaying the data. As a result, the value "50-100" is ranked last, which makes the graph very strange. One way is to define the values of the X-axis in ASCII order, but since the X-axis data is automatically and dynamically read, it is unreliable to rely on manual work. Looking at the picture above, the problem of X-axis sorting is finally solved. The code corresponding to the above figure is as follows:

plt.xticks(range(len(x)),x)
plt.plot(x,y1,label='面积与人数')


But why is the graph still so strange?

plt.xticks(range(len(x)),x)
plt.plot(y1,label='面积与人数')


Now the graphics are finally right created at:07-13-2021 robot18