【问题标题】:How to format values with comma separator in matplotlib table with an attached chart?如何在带有附加图表的 matplotlib 表中使用逗号分隔符格式化值?
【发布时间】:2019-03-29 16:43:13
【问题描述】:

我有一个 pandas 数据框,我使用 pandas.plot 函数绘制条形图。在函数中,我将表函数设置为 on。如何使用逗号分隔符格式化此随附表格中的值?

我可以对坐标轴值进行这些操作,而不是附表

我已经尝试将值转换为浮点数,但 pandas plot 只绘制整数,因此会给出错误消息“空数据框”:没有要绘制的数字数据。

ax1 = mydf.plot(kind='bar', title= chart with table, fontsize=8, width=0.75, legend=True, table=True)

ax1.legend(loc=5, bbox_to_anchor=(1.25,0.5), fontsize='x-small')

ax1.axes.get_xaxis().set_visible(False)

ax1.get_yaxis().get_major_formatter().set_scientific(False)

ax1.get_yaxis().set_major_formatter(ticker.StrMethodFormatter('${x:,.0f}'))

ax1.set_ylim(-10000000,10000000)

ax1.set_ylabel("P&L",fontsize=9)

ax1.axhline(0,0,1, color='k', linewidth=0.5)

table_ax1 = ax1.tables[0]

table_ax1.auto_set_font_size(False)

table_ax1.set_fontsize('8')

table_ax1.scale(1,2)

plt.tight_layout()

【问题讨论】:

    标签: python pandas matplotlib matplotlib-table


    【解决方案1】:

    我不知道提前在表格上强制格式化的好方法,而无需您自己明确地制作 matplotlib 表格,但是,您可以遍历表格的内容并以这种方式转换它们(如果您需要使用 pandas 实现)。我在this related question 中添加了一些代码,演示了如何操作表格。

    import pandas as pd
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(1,1, figsize = (5,5))
    df= pd.DataFrame({'City': ['LA', 'SF', 'Dallas'],
     'Lakes': [10000, 90000, 600000], # lets set some that can be comma formatted
     'Rivers': [1, 0, 0],
     'State': ['CA', 'CA', 'TX'],
     'Waterfalls': [200500, 450000, 50000]})
    
    
    
    myplot = df.plot(x=['City','State'],kind='bar',stacked='True',table=True, ax =ax)
    
    ### you can also scale and change the table
    ### see https://stackoverflow.com/questions/39668665/format-a-table-that-was-added-to-a-plot-using-pandas-dataframe-plot
    myplot.axes.get_xaxis().set_visible(False)
    # Getting the table created by pandas and matplotlib
    table = myplot.tables[0]
    # Setting the font size
    table.set_fontsize(12)
    # Rescaling the rows to be more readable
    table.scale(1,2)
    
    
    ## to format the table values I will retrieve them and change them when they aren't text labels
    xtls = ax.get_xticklabels()
    xtls = [i.get_text() for i in xtls]
    
    ax.set_xticklabels([])
    
    t = ax.tables[0]
    for c in t.get_children():
        tobj = c.get_text()
        text = tobj.get_text()
        if text not in xtls:
            try: # some texts will be strings that are labels, we can't convert them
                s = '{:0,d}'.format(int(text))
                tobj.set_text(s)
            except:
                pass
    

    【讨论】:

    • 嗨,谢谢,但上面的方法对我不起作用,它仍然给出与以前相同的结果。我真的需要格式像带有表格的熊猫条形图的样子。仅使用 Matplot lib 可以轻松复制吗?我应该澄清一下,我对 Python 真的很陌生
    • 我将添加一个完整的示例,如果这实现了您的目标,您可以告诉我!
    • 如果上述内容不适合您的用例,或者我误解了问题,请发布您的绘图的最低工作示例(带有一些示例数据),以便我们可以复制您的错误消息。
    • 您好,感谢您到目前为止的帮助,但不幸的是,此修复对我不起作用。我没有收到错误消息,而是继续生成没有逗号分隔符的图表。我想我可能不得不接受你之前的建议,并明确地使用 Matplotlib 而不是通过 pandas 重建我的图表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多