簡體   English   中英

繪制不同長度的數組

[英]Plot arrays of different lengths

我正在繪制三種不同算法的誤差與迭代次數。 它們需要不同數量的迭代來計算,因此數組的長度不同。 但我想在同一塊情節上繪制所有三條線。 目前,當我使用以下代碼時出現此錯誤:

import matplotlib.pyplot as plt

plt.plot(ks, bgd_costs, 'b--', sgd_costs, 'g-.', mbgd_costs, 'r')
plt.title("Blue-- = BGD, Green-. = SGD, Red=MBGD")
plt.ylabel('Cost')
plt.xlabel('Number of updates (k)')
plt.show()

錯誤:

    plt.plot(ks, bgd_costs, 'b--', sgd_costs, 'g-.', mbgd_costs, 'r')
  File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/pyplot.py", line 2995, in plot
    ret = ax.plot(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/axes/_axes.py", line 1331, in plot
    for line in self._get_lines(*args, **kwargs):
  File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/axes/_base.py", line 312, in _grab_next_args
    for seg in self._plot_args(remaining[:isplit], kwargs):
  File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/axes/_base.py", line 281, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "/Library/Python/2.7/site-packages/matplotlib-1.4.x-py2.7-macosx-10.9-intel.egg/matplotlib/axes/_base.py", line 223, in _xy_from_xy
    raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension

UPDATE

感謝@ ibizaman的回答,我制作了這個情節: 在此輸入圖像描述

如果我沒有弄錯的話,使用像你一樣的情節繪制3個圖表,每個圖表, ksxbgd_costssgd_costsmbgd_costs為3個不同的y 你顯然需要xy具有相同的長度和你一樣,並且錯誤說,情況並非如此。

為了使其工作,您可以添加“保持”並拆分圖表的顯示:

import matplotlib.pyplot as plt

plt.hold(True)
plt.plot(bgds, bgd_costs, 'b--')
plt.plot(sgds, sgd_costs, 'g-.')
plt.plot(mgbds, mbgd_costs, 'r')
plt.title("Blue-- = BGD, Green-. = SGD, Red=MBGD")
plt.ylabel('Cost')
plt.xlabel('Number of updates (k)')
plt.show()

注意不同的x軸。

如果您不添加暫停,則每個繪圖將首先刪除該圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM