首页 > 解决方案 > Matplotlib 趋势图

问题描述

我有以下列表:

input = ['"25', '"500', '"10000', '"200000', '"1000000']
inComp = ['0.000001', '0.0110633', '4.1396405', '2569.270532', '49085.86398']
quickrComp=['0.0000001', '0.0003665', '0.005637', '0.1209121', '0.807273']
quickComp = ['0.000001', '0.0010253', '0.0318653', '0.8851902', '5.554448']
mergeComp = ['0.000224', '0.004089', '0.079448', '1.973014', '13.034443']

我需要创建一个趋势图来演示 inComp、quickrComp、quickComp、mergeComp 的值随着输入值的增长(输入是 x 轴)的增长。我正在使用 matplotlib.pyplot,以及以下代码:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(input,quickrComp, label="QR")
ax.plot(input,mergeComp, label="merge")
ax.plot(input, quickComp, label="Quick")
ax.plot(input, inComp, label="Insrção")
ax.legend()
plt.show()

然而,实际情况是这样的:y 轴的值是无序的;首先插入 y 轴上 quickrComp 的值;然后是所有的 mergeComp 值等等。我需要 y 轴值从 0 开始并以 4 行值的最高值结束。我怎样才能做到这一点?

标签: pythonmatplotlib

解决方案


两件事:首先,您的 y 值是字符串。您需要将数据转换为数字 ( float) 类型。其次,与其余三个列表相比,您在其中一个列表中的 y 值很大。因此,您必须将 y 比例转换为对数才能看到趋势。原则上,您也可以将 x 值转换为浮点数(整数),但在您的示例中,您不需要它。如果您想这样做,您还必须"从每个 x 值的前面删除 。

请注意:不要将变量命名为与内置函数相同的名称。例如,在您的情况下,您应该重命名input为其他input1名称。

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

input1 = ['"25', '"500', '"10000', '"200000', '"1000000']
inComp = ['0.000001', '0.0110633', '4.1396405', '2569.270532', '49085.86398']
quickrComp=['0.0000001', '0.0003665', '0.005637', '0.1209121', '0.807273']
quickComp = ['0.000001', '0.0010253', '0.0318653', '0.8851902', '5.554448']
mergeComp = ['0.000224', '0.004089', '0.079448', '1.973014', '13.034443']


ax.plot(input1, list(map(float, quickrComp)), label="QR")
ax.plot(input1, list(map(float, mergeComp)), label="merge")
ax.plot(input1, list(map(float, quickComp)), label="Quick")
ax.plot(input1, list(map(float, inComp)), label="Insrção")
ax.set_yscale('log')
ax.legend()
plt.show()

在此处输入图像描述


推荐阅读