gpt4 book ai didi

python - 向 matplotlib 坐标轴添加外观合理的表格(HTML?)

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:50 25 4
gpt4 key购买 nike

我想制作一个由两部分组成的图形。在左边,我想要一个可视化(我已经知道如何制作)。在右侧,我想放置一个表格,其中包含关于图表所涵盖的同一主题的更多数字数据。假设我使用 axes[0] 进行可视化设置,并使用 axes[1] 作为我想要表格的位置。

我正在使用 Pandas,并且我在一个漂亮整洁的 DataFrame 中拥有我想要的所有信息。 (现在,我们假设 DataFrame 在行和列上都有一个常规的 Index,而不是 MultiIndex,但我很好奇如果我们放弃这个假设,答案会如何改变。)我们称之为 tabledf

采用 tabledf 并将其绘制在 axes[1] 上的最简单方法是什么?特别是,如果它看起来像 tabledf 的 HTML 表示,那就太好了。有没有办法将 HTML 表格绘制到一组 matplotlib 轴上?

我当然可以做这样的事情:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

np.random.seed(1)

tabledf = pd.DataFrame(data=np.random.randn(5,3),
index=list('abcde'),
columns=list('xyz'))



fig, axes = plt.subplots(1, 2, figsize=(20, 5))
x = np.linspace(0, 2*np.pi, 100)
axes[0].plot(x, np.sin(x))
axes[1].axis('off')
axes[1].table(cellText=tabledf.values, loc='center')

这让我: enter image description here

我有两个问题。 1)这太可怕了。 2) 如果我想将行标签和列标签移植到这个结构上,我必须做很多数组粘合。我认为必须有更好的方法。


编辑:理想情况下,右侧的表格部分看起来就像 tabledf 的默认 Pandas HTML 表示:

enter image description here

最佳答案

据我所知,使用 HTML 和 matplotlib 没有简单的方法。但是,您应该能够使用 LaTeX 来完成。

import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams["text.usetex"] = True
mpl.rcParams["text.latex.preamble"].append(r'\usepackage{tabularx}')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1], [1,0])

ax.text(.5, .5, r'''\begin{tabular}{ | l | l | l | l | } \hline & x & y & z \\\hline a & 1.62 & -0.61 & -0.528 \\\hline \end{tabular}''')

创造:

enter image description here

当然,您可以并且应该使用一些简单的代码从您的数据生成表格。一旦您掌握了 LaTeX 表格的构建方式,它们就会非常灵活。

要使上述解决方案有效,您需要在您的机器中配置良好的 LaTeX 发行版。

关于python - 向 matplotlib 坐标轴添加外观合理的表格(HTML?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25454109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com