为什么图表上的折线起点不同?

我正在尝试比较图表上的两个熊猫列。它们具有相同的长度(18个数字)。

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

# Data for plotting
t = range(1, 19)
q3 = data['Q3'].tolist()
q2= data['Q2'].tolist()

fig, ax = plt.subplots()

ax.plot(t, q2, q3)

ax.set(xlabel='# Product', ylabel='Mean in %',
       title='Results difference')
ax.grid()

plt.show()

And so on the output I see that somehow the q2 result is slightly moved by one x-tick to the left. enter image description here

评论
zquam
zquam

Calling ax.plot(t, q2, q3) will plot q2 on the y-axis with t as x-axis. And q3 also on the y-axis, but without an explicit x-axis. When none is given, the default is to use 0,1,2,... as x-axis.

To use t both for q2 and for q3, call it as ax.plot(t, q2, t, q3).

以下示例显示了区别:

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(1, 19)
q2 = np.random.randint(2, 10, 18)
q3 = np.random.randint(2, 10, 18)

fig, axs = plt.subplots(ncols=2)

axs[0].plot(t, q2, q3)
axs[0].set_title("plot(t, q2, q3)")
axs[1].plot(t, q2, t, q3)
axs[1].set_title("plot(t, q2, t, q3)")
plt.show()

example plot

点赞
评论