【问题标题】:How to Display Dataframe next to Plot in Jupyter Notebook如何在 Jupyter Notebook 中的绘图旁边显示数据框
【发布时间】:2017-12-30 09:35:57
【问题描述】:

我了解如何在 Jupyter Notebook 中显示两个相邻的图(水平),但我不知道是否有办法显示旁边有数据框的图。我想它可能看起来像这样:

但是,我无法做到这一点,并且每当我打印出数据框时,它都会出现在我的绘图下方...

Here 是一个类似的问题,但我也在同一个单元格中输出我想要垂直定向的图。

我目前有这个:

# line plots
df_plot[['DGO %chg','DLM %chg']].plot(figsize=(15,5),grid=True)
plt.ylim((-ylim,ylim))

df_plot[['Diff']].plot(kind='area',color='lightgrey',figsize=(15,1))
plt.xticks([])
plt.xlabel('')
plt.ylim((0,ylim_diff))
plt.show()

# scatter plots
plt.scatter(x=df_scat[:-7]['DGO'],y=df_scat[:-7]['DLM'])
plt.scatter(x=df_scat[-7:]['DGO'],y=df_scat[-7:]['DLM'],color='red')
plt.title('%s Cluster Last 7 Days'%asset)
plt.show()

# display dataframe
# display(df_scat[['DGO','DLM']][:10]) <-- prints underneath, not working

红色框显示我希望数据框出现的位置。有人对如何做到这一点有任何想法吗?

感谢您的意见!

【问题讨论】:

    标签: python python-2.7 pandas matplotlib jupyter-notebook


    【解决方案1】:

    我不知道如何控制 DataFrame 直接显示的位置 - 但我过去使用的一种解决方法是将 DataFrame 呈现为 matplotlib 表,然后它应该像任何其他 matplotlib阴谋。您可以使用:

    import matplotlib.pyplot as plt
    from matplotlib import six
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame()
    df['x'] = np.arange(0,11)
    df['y'] = df['x']*2
    
    fig = plt.figure(figsize=(8,5))
    
    ax1 = fig.add_subplot(121)
    ax1.scatter(x=df['x'],y=df['y'])
    
    ax2 = fig.add_subplot(122)
    font_size=14
    bbox=[0, 0, 1, 1]
    ax2.axis('off')
    mpl_table = ax2.table(cellText = df.values, rowLabels = df.index, bbox=bbox, colLabels=df.columns)
    mpl_table.auto_set_font_size(False)
    mpl_table.set_fontsize(font_size)
    

    【讨论】:

    • 有趣,这可能行得通!出于好奇,您是否需要将 plt 保存为图片才能使用?
    • 我认为您不需要将 plt 保存为图片 - 这就是我设置它的方式。如果您愿意,可以删除该行。只需调用函数“render_mpl_table(df, 'df')”将显示 matplotlib 表。许多代码使表格“漂亮”,因此您可能不需要它。
    • 这非常适合将数据框打印为斧头...您知道如何将其包含为子图吗?我正在使用 plt.subplot(1,2,1)plt.subplot(1,2,2) 但不知道如何做相当于 plt.ax
    • OK @DavidYang 我想通了——基本上你只需要把桌子拉到函数之外。我还使表格输出更加清晰。
    【解决方案2】:

    另一种可能性是使用 html 来订购东西,遵循https://stackoverflow.com/a/44923103/4908900

    这是一个工作示例,(可能有更优雅的方法):

    prefix = \
    """
     <!DOCTYPE html>
    <html>
    <head>
    <style>
    * {
        box-sizing: border-box;
    }
    
    .column {
        float: left;
        width: 33.33%;
        padding: 5px;
    }
    
    /* Clearfix (clear floats) */
    .row::after {
        content: "";
        clear: both;
        display: table;
    }
    </style>
    </head>
    <body>
    
    <h2>title</h2>
    
    <div class="row">
      <div class="column">
    """
    
    suffix = \
    """
      </div>
      <div class="column">
        <img src="pic_file.png" alt="Graph" style="width:100%">
      </div>
    </div>
    </body>
    </html>
    """
    
    df = pd.DataFrame(np.arange(36).reshape((6,6)),columns=['A','B','C','D','E','F'])
    ax = df.plot(lw=4)
    title = "mock data"
    fig = ax.get_figure()
    fig.savefig(title+".png")
    html = prefix.replace('title', title)+df.to_html()+suffix.replace('pic_file.png', title+".png")
    display_html(html, raw=True)
    

    【讨论】:

      【解决方案3】:

      您可以使用 %matplotlib inline 然后只需编写代码 前 df.head() plt.plot(df['X']) 所以 %matplotlib inline 将在一个单元格中绘制数据框以及绘图

      【讨论】:

      • 请格式化您的代码并添加一个易于理解的示例。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 2017-11-28
      • 2018-02-02
      • 2022-01-09
      • 2016-12-30
      • 2018-09-28
      • 2018-04-11
      相关资源
      最近更新 更多