如何在具有对数刻度的图中绘制“线性”趋势线

时间:2017-10-23 09:22:47

标签: python matplotlib

我试图在y轴上用对数刻度绘制线性趋势线,表明底层数据呈指数衰减。

这是我的代码:

data = self.global_objects_per_frame

(n, bins, patches) = plt.hist(data, bins=np.arange(min(data), max(data)+1), alpha=0.5, range=[0, 40])

plt.yscale('log', nonposy='clip')
plt.xlim(0, 40)

plt.title('Pedestrian Density', fontweight='bold')
plt.xlabel('# of pedestrians', fontweight='bold')
plt.ylabel('# of frames', fontweight='bold')

ax = plt.gca()

ax.yaxis.grid(which="major", color='black', linestyle=':', linewidth=1)

for axis in [ax.xaxis, ax.yaxis]:
    axis.set_major_formatter(ScalarFormatter())

x = bins.tolist()
x = x[:41]

y = n.tolist()
y = y[:41]

z = np.polyfit(x, y, 1)

p = np.poly1d(z)
plt.plot(x, p(x), "r--")

plt.savefig(os.path.join(outputPath, self.name, 'PedestrianDensity'), dpi = 300)

此代码的结果是红色虚线,但我真正想要的是红色实线。

有人可以帮我修改我的代码吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

您希望在对数缩放数据中插入一条线,而不是数据本身。因此你需要适合

z = np.polyfit(x, np.log10(y), 1)

然后你需要将拟合缩放回数据坐标,以便它出现""作为一行,

p = np.poly1d(z)
plt.plot(x, 10**p(x), "r--")