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.

sample image

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.

data structure

# 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
#df = pd.read_excel('quanguojingji10nian.xls')



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.

X-axis sorting is finally solved

Looking at the picture above, the problem of X-axis sorting is finally solved. The code corresponding to the above figure is as follows:


But why is the graph still so strange?


Now the graphics are finally right

final image

created at:07-13-2021
edited at: 07-13-2021: