在子图中创建表

时间:2015-02-23 19:29:20

标签: python matplotlib subplot

我有一个python图,然后希望在与其相邻的子图中的表中有一组统计信息。我使用了一种特殊的方法,在其中我创建了一个带有白轴颜色的子图,然后在子图中创建一个表。如果仔细观察,您可以看到表格中有白线。我的代码如下。

import pandas as pd
import numpy as np
import datetime as dt
import matplotlib.pyplot
from patsy import dmatrices
import statsmodels.api as sm
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(1, 2,width_ratios=[6,1])
ax1 = plt.subplot(gs[0])
plt.plot_date(sp_df.index,np.log(sp_df['PX_LAST']),'k')
sells = sp_df[(sp_df['hurst'] > 0.5) & (sp_df['sharpe'] < 0.5) & (sp_df['20dma'] < sp_df['65dma'])].index
buys = sp_df[(sp_df['hurst'] > 0.5) & (sp_df['sharpe'] > 0.5) & (sp_df['20dma'] > sp_df['65dma']) & (sp_df['50dma'] > sp_df['200dma'])].index
plt.plot_date(buys,np.log(sp_df.ix[buys]['PX_LAST']),'g^')
plt.plot_date(sells,np.log(sp_df.ix[sells]['PX_LAST']),'rv')
plt.xlim(sp_df.index[0] - dt.timedelta(days=90),sp_df.index[-1] + dt.timedelta(days=90))
ax2 = plt.subplot(gs[1])
total_return = 2.50
annualized_return = 1.257
sharpe_ratio = .85
max_dd = .12
dd_duration = 300
stats = {"Total Return" : "%0.2f%%" % ((total_return - 1.0) * 100.0),
                 "Annualized Return" : "%0.2f%%" %((annualized_return - 1.0) * 100.0),
                 "Sharpe Ratio" : "%0.2f" % sharpe_ratio,
                 "Max Drawdown" : "%0.2f%%" % (max_dd * 100.0),
                 "Drawdown Duration" : str(dd_duration) + " days"}
bbox=[0.0,0.0,.5, .5]
stats = pd.DataFrame(stats,index=range(1)).T
plt.table(cellText = stats.get_values(),colWidths=[0.6]*2,rowLabels=stats.index,colLabels=['Metrics'],loc='right')
plt.tick_params(axis='both',top='off',left='off',labelleft='off',right='off',bottom='off',labelbottom='off')
ax = plt.gca()
ax.spines['bottom'].set_color('white')
ax.spines['top'].set_color('white')
ax.spines['left'].set_color('white')
ax.spines['right'].set_color('white')
fig = plt.gcf()
fig.set_size_inches(11.5,8.5)

连同图片Plot with table

1 个答案:

答案 0 :(得分:1)

基于this answer,您还可以使用Latex创建表格 为了便于使用,您可以创建一个将数据转换为相应文本字符串的函数:

import numpy as np
import matplotlib.pyplot as plt
from math import pi
from matplotlib import rc

rc('text', usetex=True)

# function that creates latex-table
def latex_table(celldata,rowlabel,collabel):
    table = r'\begin{table} \begin{tabular}{|1|'
    for c in range(0,len(collabel)):
        # add additional columns
        table += r'1|'
    table += r'} \hline'

    # provide the column headers
    for c in range(0,len(collabel)-1):
        table += collabel[c]
        table += r'&'
    table += collabel[-1]
    table += r'\\ \hline'

    # populate the table:
    # this assumes the format to be celldata[index of rows][index of columns]
    for r in range(0,len(rowlabel)):
        table += rowlabel[r]
        table += r'&'
        for c in range(0,len(collabel)-2):
            if not isinstance(celldata[r][c], basestring):
                table += str(celldata[r][c])
            else:
                table += celldata[r][c]
            table += r'&'

        if not isinstance(celldata[r][-1], basestring):
            table += str(celldata[r][-1])
        else:
            table += celldata[r][-1]
        table += r'\\ \hline'

    table += r'\end{tabular} \end{table}'

    return table

# set up your data:

celldata = [[32, r'$\alpha$', 123],[200, 321, 50]]
rowlabel = [r'1st row', r'2nd row']
collabel = [r' ', r'$\alpha$', r'$\beta$', r'$\gamma$']

table = latex_table(celldata,rowlabel,collabel)

# set up the figure and subplots

fig = plt.figure()

ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

ax1.plot(np.arange(100))
ax2.text(.1,.5,table, size=50)
ax2.axis('off')

plt.show() 

这个函数的基本思想是创建一个名为table的长字符串,它可以被解释为Latex命令。导入rc并设置rc('text', uestec=True)以确保字符串可以理解为Latex非常重要。
该字符串使用+=附加;输入为原始字符串,因此为r。示例数据突出显示了数据格式 最后,通过此示例,您的图形如下所示:

table and graph