使用 matplotlib 无法正确显示图形

东丰

我有一个看起来像这样的二维列表。

list_of_Tots:
[[335.06825999999904,
  754.4677800000005,
  108.76719000000037,
  26.491620000000104,
  156.56571000000028],
 [332.8958600000008,
  613.4729919999997,
  142.58723599999996,
  48.48214800000058,
  171.39861200000016],
 ........
 [1388.2799999999681,
  670.0599999999969,
  1144.8699999999897,
  346.81999999999715,
  70.37000000000008]]

这个二维列表有 10 个列表,每个列表有 5 个数字。

我想通过在 Jupyter notebook 上使用 matplotlib 来显示每个列表的条形图,因此实现了下面的代码。

def bar_chart(y_list, x_list=['L','LC','C','RC','R']):
    x = np.array(x_list)
    y = np.array(y_list)
    plt.ylabel('Bedload[kg/m/year]')
    plt.bar(x, y)

def display_bar_charts(list_of_arraies):
    num_of_tots = len(list_of_arraies)    
    %matplotlib inline
    fig = plt.figure(figsize=(3*5, 6))
    for i, y_list in enumerate(list_of_arraies):
        bar_chart(y_list)
        ax = plt.subplot(2, 5, i+1)
        ax.set_title('Tot({})'.format(i+1))

    fig.tight_layout()

display_bar_charts(list_of_Tots)

然后我得到了这样的结果 在此处输入图片说明

我打算显示 10 个数字,因为“list_of_Tots”中有 10 个列表,但图像上只有 9 个数字。我查看了数据,结果发现图像上不存在“list_of_Tots”中的第一个列表,而第二个列表位于第一个列表应该出现的第一个位置。第三个名单在第二位……,第四个名单在第三位……最后一个地方,里面没有酒吧。

你能找出这段代码中的一些错误吗?谢谢你。

ezatterin

如评论中所述,您需要先创建一些轴,然后再在其中绘制某些内容。所以这样做并将轴传递给您的条形图函数:

def bar_chart(ax, y_list, x_list=['L','LC','C','RC','R']):
    x = np.array(x_list)
    y = np.array(y_list)
    ax.set_ylabel('Bedload[kg/m/year]')
    ax.bar(x, y)

def display_bar_charts(list_of_arraies):
    num_of_tots = len(list_of_arraies)    
    %matplotlib inline
    fig = plt.figure(figsize=(3*5, 6))
    for i, y_list in enumerate(list_of_arraies):
        ax = plt.subplot(2, 5, i+1)
        bar_chart(ax, y_list)
        ax.set_title('Tot({})'.format(i+1))

    fig.tight_layout()

否则plt.bar将查找最后一个活动轴,它们在您的 for 循环中不存在i=0,因为创建轴之前bar_chart调用

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章