【问题标题】:output table to left of horizontal bar chart with pandas带有熊猫的水平条形图左侧的输出表
【发布时间】:2018-01-02 17:37:20
【问题描述】:

我正在尝试从数据框中获取输出,该数据框显示堆叠的水平条形图,其左侧有一个表格。相关数据如下:

import pandas as pd
import matplotlib.pyplot as plt

cols = ['metric','target','daily_avg','days_green','days_yellow','days_red']
vals = ['Volume',338.65,106.81,63,2,1]

OutDict = dict(zip(cols,vals))
df = pd.DataFrame(columns = cols)
df = df.append(OutDict, ignore_index = True)

我想获得类似于以下内容的内容:Python Matplotlib how to get table only。我可以得到堆积条形图:

df[['days_green','days_yellow','days_red']].plot.barh(stacked=True)

添加关键字参数table=True 在图表下方放置一个表格。如何让轴将 df 显示为表格或在图表旁边添加一个。此外,DataFrame 最终将有不止一行,但如果我能让它为一行工作,那么我应该能够让它为 n 行工作。

提前致谢。

【问题讨论】:

    标签: python python-3.x pandas matplotlib


    【解决方案1】:

    不幸的是,使用pandas.plot 方法您将无法做到这一点。 table 参数状态的文档:

    如果为 True,则使用 DataFrame 中的数据绘制表格,数据将被转置以满足 matplotlib 的默认布局。如果传递的是Series或DataFrame,则使用传递的数据绘制表格。

    所以你必须直接使用 matplotlib 来完成这项工作。一种选择是创建 2 个子图;一个用于您的表格,一个用于您的图表。然后,您可以添加表格并根据需要进行修改。

    import matplotlib.pyplot as plt
    import pandas as pd
    
    cols = ['metric','target','daily_avg','days_green','days_yellow','days_red']
    vals = ['Volume',338.65,106.81,63,2,1]
    
    OutDict = dict(zip(cols,vals))
    df = pd.DataFrame(columns = cols)
    df = df.append(OutDict, ignore_index = True)
    
    fig, (ax1, ax2) = plt.subplots(1, 2)
    df[['days_green','days_yellow','days_red']].plot.barh(stacked=True, ax=ax2)
    ax1.table(cellText=df[['days_green','days_yellow','days_red']].values, colLabels=['days_green', 'days_yellow', 'days_red'], loc='center')
    ax1.axis('off')
    fig.show()
    

    【讨论】:

    • 谢谢,这似乎可行,现在我只需要让 ax2 与 ax1 大小相同。有没有办法让图表作为额外的列嵌入到数据框中?
    • 这可能值得另一个问题,因为我相信还有其他人比我自己更有经验,但我会指出,可以使用 @ 在您的数据框样式中包含条形图987654323@
    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2017-04-01
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多