【问题标题】:Matplotlib- Creating a table with line plots in cells?Matplotlib- 在单元格中创建带有线图的表格?
【发布时间】:2018-05-26 13:09:24
【问题描述】:

我有历史棒球数据,我试图在一个简单的 matplotlib 图中可视化 在 1 个子图中我想要一个表格,显示过去一年的平均统计数据,每个统计数据的折线图,然后是最终得分这是独立计算的。

我知道 matplotlib 有一个表函数,所以创建一个 5x3 表会很简单,但是是否可以在表中插入图作为值?如果没有,对我应该做什么有什么建议吗?我想我可以创建几个子图,但格式会很古怪而且不是很动态。感谢帮助。

使用 @TheImportanceofBeingErnest 的代码,我遇到了 matplotlib 的一个错误,我在使用 gridspec 时看不到 x 轴:

fig = plt.figure(figsize=(8.5,11))

gs_row1left = gridspec.GridSpec(1,1)
gs_row1right = gridspec.GridSpec(1,1)

summaryplot2subplot(fig, gs_row1left[0], data, col1, col2, finalsc)
ax.axis('off')

ax2 = fig.add_subplot(gs_row1right[0, 0])
df = pd.DataFrame({'year':['2001-01','2002-01','2003-01','2004-01','2005-01'], 'value':[100,200,300,400,500]})

barax = ax2.twinx()
df['value1']= df['value']*0.4

df['value2'] = df['value']*0.6# Let them be strings!



df.plot(x = ['year'], y = ['value'], kind = 'line', ax = ax2)

df.plot(x = ['year'], y= ['value1','value2'], kind = 'bar', ax = barax)



gs_row1left.update(left = 0.05, right = 0.48)
gs_row1right.update(left = 0.55, right = 0.98)
plt.show()

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:

    无法将绘图插入到 matplotlib 表中。然而,子图网格允许创建类似表格的行为。

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = np.random.rand(100,4)
    col1 = ["WAR", "ERA", "IP", "WHIP", "Final\nScore"]
    col2 = [0.23,1.60,0.28,0.02,0.38]
    col2colors = ["red", "g", "r", "r", "r"]
    finalsc = "D+"
    
    fig, axes = plt.subplots(ncols=3, nrows=5, figsize=(4,2.6),
                             gridspec_kw={"width_ratios":[1,0.5,2]})
    fig.subplots_adjust(0.05,0.05,0.95,0.95, wspace=0.05, hspace=0)
    
    for ax in axes.flatten():
        ax.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0)
        ax.ticklabel_format(useOffset=False, style="plain")
        for _,s in ax.spines.items():
            s.set_visible(False)
    border = fig.add_subplot(111)
    border.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0)
    border.set_facecolor("None")
    
    text_kw = dict(ha="center", va="bottom", size=13)
    for i,ax in enumerate(axes[:,0]):
        ax.text(0.5, 0.05, col1[i], transform=ax.transAxes, **text_kw)
    for i,ax in enumerate(axes[:,1]):
        ax.text(0.5, 0.05, "{:.2f}".format(col2[i]),transform=ax.transAxes, **text_kw)
        ax.set_facecolor(col2colors[i])
        ax.patch.set_color(col2colors[i])
    axes[-1,-1].text(0.5, 0.05, finalsc,transform=axes[-1,-1].transAxes, **text_kw)
    
    for i,ax in enumerate(axes[:-1,2]):
        ax.plot(data[:,i], color="green", linewidth=1)
    
    
    plt.show()
    

    要将几个这样的图放入一个图中,您可以稍微不同地处理它并创建一个包含多个子网格的 gridspec。

    import matplotlib.pyplot as plt
    from matplotlib import gridspec
    import numpy as np
    
    
    def summaryplot2subplot(fig, gs, data, col1, col2, finalsc):
        col2colors = ["g" if col2[i] > 1 else "r" for i in range(len(col2)) ]
        sgs = gridspec.GridSpecFromSubplotSpec(5,3, subplot_spec=gs, wspace=0.05, hspace=0,
                                               width_ratios=[0.9,0.7,2])
        axes = []
        for n in range(5):
            for m in range(3):
                axes.append(fig.add_subplot(sgs[n,m]))
        axes = np.array(axes).reshape(5,3)
        for ax in axes.flatten():
            ax.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0)
            ax.ticklabel_format(useOffset=False, style="plain")
            for _,s in ax.spines.items():
                s.set_visible(False)
        border = fig.add_subplot(gs)
        border.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0)
        border.set_facecolor("None")
        
        text_kw = dict(ha="center", va="bottom", size=11)
        for i,ax in enumerate(axes[:,0]):
            ax.text(0.5, 0.05, col1[i], transform=ax.transAxes, **text_kw)
        for i,ax in enumerate(axes[:,1]):
            ax.text(0.5, 0.05, "{:.2f}".format(col2[i]),transform=ax.transAxes, **text_kw)
            ax.set_facecolor(col2colors[i])
            ax.patch.set_color(col2colors[i])
        axes[-1,-1].text(0.5, 0.05, finalsc,transform=axes[-1,-1].transAxes, **text_kw)
        
        for i,ax in enumerate(axes[:-1,2]):
            ax.plot(data[:,i], color=col2colors[i], linewidth=1)
    
    
    fig = plt.figure(figsize=(8,6))
    gs = gridspec.GridSpec(2,2)
    
    
    col1 = ["WAR", "ERA", "IP", "WHIP", "Final\nScore"]
    finalsc = "D+"
    
    for i in range(4):
        data = np.random.rand(100,4)
        col2 = np.random.rand(5)*2
        summaryplot2subplot(fig, gs[i], data, col1, col2, finalsc)
    
    plt.show()

    【讨论】:

    • 这正是我所需要的——谢谢!我可能正在运行旧版本的 matplotlib,但由于某种原因,我不得不为 set_facecolor 插入一个路径,即ax.patch.set_facecolor(col2colors[i])
    • 我正在尝试将此图作为 4x2 网格中其他图的子图。你知道这是否可能,因为我们已经在这个例子中使用了子图?感谢帮助
    • 太棒了-非常感谢!因此,如果我只是想将其中一个插入另一个图中(我基本上只想在更大的图中有一个图表),我将如何将所有这些放入一个斧头?我必须使用 gridspec 吗?
    • 较大的情节需要使用gridspec。但它只对这种类似表格的情节是必要的,所有其他子情节也可能以不同的方式创建。
    • 那么是否有可能将所有这些都放在一把斧头上,其中斧头类似于ax = fig.add_subplot(4,2,1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多