Pyomo 使用 matplotlib 可视化数据

Pyomo visualizing data with matplotlib

我已经解决了一个模型并尝试使用 matplolib 可视化结果。

这个模型可以运行正常。我正在尝试修复变量并重新求解该模型并输出三个不同的条形图以便与其他条形图进行比较。 但是我用matplotlib画条形图的时候,只画了最后一张(cost 20171.984)

如何输出三种不同的条形图?

到目前为止我所做的是这样的:

for s in [800, 1000, 1200]:
    instance.demand = s
    opt = SolverFactory('Ipopt')
    results = opt.solve(instance)
    print('Cost: ', value(instance.cost))

# cost printed
Cost:  13139.706753161874
Cost:  16460.857089915964
Cost:  20171.984469196814

# Matplotlib
plt.figure(figsize=(8, 6))
x = [0.1]
plt.bar(x, value(instance.cost), alpha=0.7, width=0.015).........Code omitted in this part

你能帮我吗?谢谢!

3 个成本,1 个图表:

import matplotlib.pyplot as plt
%matplotlib inline

xlabels = ["bar1","bar2", "bar3"]
costs = [13139, 16460, 33333]

bar = plt.bar(xlabels, costs, width=0.8, color=['blue', 'red', 'green'])
plt.xticks(range(len(xlabels)), xlabels)

plt.ylabel("Costs")
plt.xlabel("X label")
plt.legend((bar[0], bar[1], bar[2]), xlabels, loc="upper right")
plt.title("My chart")
plt.show()

你可以试试:

costs = []
for s in [800, 1000, 1200]:
    instance.demand = s
    opt = SolverFactory('Ipopt')
    results = opt.solve(instance)
    print('Cost: ', value(instance.cost))
    costs.append(value(instance.cost))

然后您将得到列表 costs,您可以按照上一个答案所示绘制它。