绘制不同长度的数组 [英] Plot arrays of different lengths

查看:66
本文介绍了绘制不同长度的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制三种不同算法的误差与迭代次数.它们需要执行不同数量的迭代,因此数组的长度不同.但是我想在同一个图上绘制所有三条线.目前,当我使用以下代码时会出现此错误:

I'm plotting the error vs. number of iterations for three different algorithms. They take a different number of iterations to compute, so the arrays are of different length. Yet I want to plot all three lines on the same plot. Currently, I get this error when I use the following code:

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

更新

感谢@ibizaman 的回答,我绘制了这个图:

Thanks to @ibizaman's answer, I made this plot:

推荐答案

如果我没记错的话,像你一样使用 plot 绘制 3 个图,对于每个图,ksxbgd_costssgd_costsmbgd_costs 作为 3 个不同的 y.您显然需要 xy 具有相同的长度,并且就像您和错误所说的那样,情况并非如此.

If I'm not mistaken, using plot like you did plots 3 graphs with, for each, ks as x and bgd_costs, sgd_costs and mbgd_costs as 3 different y. You obviously need x and y to have the same length and like you and the error says, it's not the case.

为了让它工作,你可以添加一个保持"和一个分割图的显示:

To make it work, you could add a "hold" and a split the display of the plots:

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 轴.

如果不添加保留,则每个绘图都会先删除图形.

If you don't add a hold, every plot will erase the figure first.

这篇关于绘制不同长度的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆