Home > Enterprise >  Can matplotlib plot decreasing arrays?
Can matplotlib plot decreasing arrays?

Time:05-20

I am processing some data collected in a driving simulator, and I needed to plot the velocity against the location. I managed to convert the velocity and location values into 2 numpy arrays. Due to the settings of the simulator, the location array is continuously decreasing. The sample array is [5712.114 5711.662 5711.209 ... 3185.806 3185.525 3185.243]. Similarly, the velocity array is also decreasing because we were testing the brake behavior. Example array: [27.134 27.134 27.134 ... 16.87 16.872 16.874].

So, when I plot these 2 arrays, what I should see should be a negatively sloped line, and both x and y axis should have decreasing numbers. I used the code below to plot them:

plotting_x = np.array(df["SubjectX"].iloc[start_index-2999:end_index 3000])
plotting_y = np.array(df["Velocity"].iloc[start_index-2999:end_index 3000])
plt.plot(plotting_x, plotting_y, "r")

What I saw is a graph attached here. Anyone know what went wrong? Does Matplotlib not allow decreasing series? Thanks! Matplotlib plot

CodePudding user response:

The problem is that by default matplotlib always defines the x axis increasing, so it will map the points following that rule. Try to reverse it by dong:

ax = plt.gca()
ax.invert_xaxis()

After the plot call.

CodePudding user response:

From what I understand, since both the position and the velocity are decreasing, there is nothing wrong with the plot, simply the first point is in the top right corner and the last is in the bottom left.

At a first glance, I would also say that the position is always decreasing (the vehicle never jumps back) while the velocity has a more interesting behaviour.

You can check if this is the case plotting in two steps with two colours:

plotting_x = np.array(df["SubjectX"].iloc[start_index-2999:end_index])
plotting_y = np.array(df["Velocity"].iloc[start_index-2999:end_index])
plt.plot(plotting_x, plotting_y, "r", label="first")

and

plotting_x = np.array(df["SubjectX"].iloc[start_index:end_index 3000])
plotting_y = np.array(df["Velocity"].iloc[start_index:end_index 3000])
plt.plot(plotting_x, plotting_y, "b", label="second")

then:

plt.legend()
plt.show()

To get a more usual representation you can revert the axis or use:

plotting_x = some_number - np.array(df["SubjectX"].iloc[start_index-2999:end_index 3000])
  • Related