在子图中创建表 [英] Create Table in subplot

查看:20
本文介绍了在子图中创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python绘图,然后希望在与其相邻的子图中的表中具有一组统计信息.我使用了一种临时方法,在该方法中我创建了一个带有白色轴颜色的子图,然后在子图中制作了一个表格.如果仔细观察,您会看到桌子上有白线贯穿其中.我的代码如下.

I have a python plot and then would like to have a set of statistics in a table in a subplot adjacent to it. I have used kind of an adhoc approach in which I create a subplot with white axis colors and then make a table in the subplot. You can see that the table has white lines running through it if you look closely. My code is below.

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)

连同图片

推荐答案

基于此答案,您也可以使用Latex创建一个表.
为了便于使用,您可以创建一个将数据转换为相应文本字符串的函数:

Based on this answer you can also use Latex to create a table.
For ease of usability, you can create a function that turns your data into the corresponding text-string:

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 .示例数据突出显示了数据格式.
最后,在此示例中,您的图形如下所示:

The underlying idea of this function is to create one long string, called table which can be interpreted as a Latex-command. It is important to import rc and set rc('text', uestec=True) to ensure that the string can be understood as Latex.
The string is appended using +=; the input is as raw string, hence the r. The example data highlights the data format.
Finally, with this example, your figure looks like this:

这篇关于在子图中创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆