gpt4 book ai didi

python多行为一组

转载 作者:行者123 更新时间:2023-11-28 18:29:40 25 4
gpt4 key购买 nike

如果我用一个调用绘制各种不相交的线如下...

>>> import matplotlib.pyplot as plt
>>> x = [random.randint(0,9) for i in range(10)]
>>> y = [random.randint(0,9) for i in range(10)]
>>> data = []
>>> for i in range(0,10,2):
... data.append((x[i], x[i+1]))
... data.append((y[i], y[i+1]))
...
>>> print(data)
[(6, 4), (4, 3), (6, 5), (0, 4), (0, 0), (2, 2), (2, 0), (6, 5), (2, 5), (3, 6)]
>>> plt.plot(*data)
[<matplotlib.lines.Line2D object at 0x0000022A20046E48>, <matplotlib.lines.Line2D object at 0x0000022A2004D048>, <matplotlib.lines.Line2D object at 0x0000022A2004D9B0>, <matplotlib.lines.Line2D object at 0x0000022A20053208>, <matplotlib.lines.Line2D object at 0x0000022A20053A20>]
>>> plt.show()

enter image description here

我无法弄清楚如何让 python/matplotlib 将其视为单个图,具有相同的颜色、线宽等和相同的图例条目...

提前谢谢你

最佳答案

如果您不介意将它们全部合并为一行,那么您应该简单地使用 plt.plot(x,y)。但是我认为您希望将它们保留为单独的行。为此,您可以为绘图命令指定样式参数,然后使用 Stop matplotlib repeating labels in legend 中的代码以防止出现多个图例条目。

import matplotlib.pyplot as plt
import numpy as np
from collections import OrderedDict

x = [np.random.randint(0,9) for i in range(10)]
y = [np.random.randint(0,9) for i in range(10)]
data = []
for i in range(0,10,2):
data.append((x[i], x[i+1]))
data.append((y[i], y[i+1]))

#Plot all with same style and label.
plt.plot(*data,linestyle='-',color='blue',label='LABEL')

#Single Legend Label
handles, labels = plt.gca().get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())

#Show Plot
plt.show()

给你
enter image description here

关于python多行为一组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38400403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com