如何在带有图表的matplotlib表中用逗号分隔符格式化值?

2024-04-18 20:17:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我可以对轴值执行这些操作,但不能对随附的表执行这些操作

我已经尝试过将值转换为float,但是pandas plot只绘制整数,因此会出现一个错误,即“Empty Dataframe”:没有要绘制的数字数据。在

轴1=mydf.绘图(kind='bar',title=带表格的图表,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()

Tags: 数据函数falsetruepandasgetplottable
1条回答
网友
1楼 · 发布于 2024-04-18 20:17:29

我不知道有什么好方法可以在不显式地生成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

result

相关问题 更多 >