首页 > 解决方案 > 如何绘制从列表列表中提取的数据?

问题描述

我有一个列表包含像这个例子这样的数据

data=[[january-b1,0.25,0.33],[february-b1,0.254,0.9],...,[august-b1,0.1,0.13],[january-b2,0.25,0.33],[february-b2,0.254,0.9],...,[august-b3,0.1,0.13]....]

每个月有 10 个波段 b1..b10 和 2 个值。我想将每个波段的变化绘制为月份的函数。每个波段有两个数字:第一个值和第二个值的变化。

标签: pythonmatplotlib

解决方案


这可能是第一个近似值

import matplotlib.pyplot as plt

#plt.clf()
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.title("My plot")

data=[["january-b1",0.25,0.33],["february-b1",0.254,0.9],["august-b1",0.1,0.13]]
labels,l_v1,l_v2 = [],[],[]
for l,v1,v2 in data:
    labels.append(l)
    l_v1.append(v1)
    l_v2.append(v2)
plt.plot(range(len(labels)), l_v1,linestyle='--', marker='o', color='blue')
plt.plot(range(len(labels)), l_v2, linestyle='--', marker='o', color='red')
plt.xticks(range(len(labels)),labels)
#plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()

在此处输入图像描述

另一种可能的解决方案(每行代表一个月)。按月有2条线,同月变量线的颜色相似。

import matplotlib.pyplot as plt

#plt.clf()
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.title("My plot")
colors = [
    "red", "orange", "blue", "purple", "yellow", "olive", "aqua",
    "red", "orange", "blue", "purple", "yellow", "olive"
]
data = [["january-b1", 0.25, 0.33], ["january-b2", 0.23, 0.33],["january-b3", 0.25, 0.33],
        ["february-b1", 0.254, 0.9],["february-b2", 0.274, 0.79],["february-b3", 0.254, 0.94],
        ["august-b1", 0.12, 0.13],["august-b2", 0.1, 0.13],["august-b3", 0.0, 0.23]]


variables_dict_1 = {}
variables_dict_2 = {}
for l,v1,v2 in data:
    label = l.split("-")[0]
    pos = l.split("-")[1].split("b")[-1]
    print(pos)
    pos = int(pos)-1

    aux = variables_dict_1.get(label,[0]*3) #change * 13 in your data
    aux[pos] = v1
    variables_dict_1[label] = aux

    aux = variables_dict_2.get(label, [0] * 3)  #change * 13 in your data
    aux[pos] = v2
    variables_dict_2[label] = aux

colors = [("red","salmon"),("blue","steelblue"),("orange","goldenrod")]
print(variables_dict_1.keys())
print(variables_dict_1)

for i,l in enumerate(variables_dict_1.keys()):
    plt.plot(range(len(variables_dict_1[l])), variables_dict_1[l],linestyle='--', marker='o', color=colors[i][0])
    plt.plot(range(len(variables_dict_1[l])), variables_dict_2[l], linestyle='--', marker='o', color=colors[i][1])
#plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()

在此处输入图像描述


推荐阅读