如何利用Python自动生成数据绘制折线图

1.导入库

    直接导入matplotlib库。

import matplotlib.pyplot as plt

2.数据准备

    用list分别准备横坐标和纵坐标的数据。

X1 = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Y1 = [971,1344,1953,3064,4766,15522,4389,2615,1696,1210,798]
X2 = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Y2 = [554,861,1238,1979,3206,10663,2916,1639,1047,704,489]
X3 = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Y3 = [363,547,801,1254,2205,7535,1984,1115,677,464,340]
X4 = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Y4 = [293,478,681,1070,1819,6563,1750,953,583,410,287]

3.图像绘制

    直接绘制折线图。

plt.figure()

# X1的分布
plt.plot(X1, Y1, label="X1", color="#FF3B1D", marker='*', linestyle="-")

# X2的分布
plt.plot(X2, Y2,label="X2",  color="#3399FF", marker='o', linestyle="-")

# X3的分布
plt.plot(X3, Y3, label="X3",  color="#F9A602", marker='s', linestyle="-")

# X4的分布
plt.plot(X4, Y4, label="X4",  color="#13C4A3", marker='d', linestyle="-")
# plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(1))   # 将横坐标的值全部显示出来
X_labels = ['-5','-4','-3','-2','-1','0','1','2','3','4','5']
plt.xticks(X1,X_labels,rotation=0)
plt.legend()
plt.title("Lake.bmp")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

    上述结果亲测有效。

4.完整代码(直接复制可运行)

import matplotlib.pyplot as plt
X1 = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Y1 = [971,1344,1953,3064,4766,15522,4389,2615,1696,1210,798]
X2 = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Y2 = [554,861,1238,1979,3206,10663,2916,1639,1047,704,489]
X3 = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Y3 = [363,547,801,1254,2205,7535,1984,1115,677,464,340]
X4 = [-5,-4,-3,-2,-1,0,1,2,3,4,5]
Y4 = [293,478,681,1070,1819,6563,1750,953,583,410,287]

plt.figure()

# X1的分布
plt.plot(X1, Y1, label="X1", color="#FF3B1D", marker='*', linestyle="-")

# X2的分布
plt.plot(X2, Y2,label="X2",  color="#3399FF", marker='o', linestyle="-")

# X3的分布
plt.plot(X3, Y3, label="X3",  color="#F9A602", marker='s', linestyle="-")

# X4的分布
plt.plot(X4, Y4, label="X4",  color="#13C4A3", marker='d', linestyle="-")
# plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(1))   # 将横坐标的值全部显示出来
X_labels = ['-5','-4','-3','-2','-1','0','1','2','3','4','5']
plt.xticks(X1,X_labels,rotation=0)
plt.legend()
plt.title("Lake.bmp")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

你可能感兴趣的:(python,matplotlib,开发语言)