【问题标题】:Graphs don't appear correctly with matplotlibmatplotlib 无法正确显示图形
【发布时间】:2019-12-28 12:19:17
【问题描述】:

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

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”中的第一个列表,而第二个列表位于第一个列表应该位于的第一个位置。第三个列表排在第二位……第四个列表排在第三位……而在最后一个位置,里面没有横杠。

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

【问题讨论】:

  • 在实际绘制某些东西之前,您需要定义要绘制的轴。

标签: python-3.x list matplotlib bar-chart subplot


【解决方案1】:

正如评论中提到的,您需要先创建一些轴,然后再在其中绘制一些东西。所以这样做并将轴传递给您的条形图功能:

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 将查找最后一个活动轴,这些轴在i=0 的循环中不存在,因为在创建轴之前调用了bar_chart

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 2021-05-09
    相关资源
    最近更新 更多