Jsg*_*g91 15 python matplotlib
我正在尝试使用matplotlib创建一个表,我已经设法获取我的数据,但我正在努力进行最终格式化.我需要编辑图形的大小以包含我的所有数据,因为有些内容正在被删除.这是我目前的代码:
for struct, energy, density in clust_data:
fig=plt.figure()
ax = plt.gca()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
colLabels=("Structure", "Energy", "Density")
rows=len(clust_data)
cellText=[]
for row in clust_data:
cellText.append(row)
the_table = ax.table(cellText=cellText,
colLabels=colLabels,
loc='center')
plt.savefig("table.png")
Run Code Online (Sandbox Code Playgroud)
这会创建一个像这样的表(我不完全确定如何通过某些行来获取行):

任何帮助是极大的赞赏!
Fra*_*ano 12
您应该能够解决您的问题,执行以下操作:
图大小(编辑):
hcell=0.3,wcell=1)len(clust_data)+13)创建具有正确大小的图形(您可能需要一些额外的填充)
fig = plt.figure(figsize=(3*wcell+wpad, nrows*hcell+hpad))
Run Code Online (Sandbox Code Playgroud)两行内的线是轴刺.
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
Run Code Online (Sandbox Code Playgroud)
只需隐藏轴标签和刻度线,而不是轴刺.您必须隐藏它们或将它们涂成白色
看下面的完整解决方案
在任何情况下:我认为你做了很多无用的操作.从你的代码片段来看,在我看来,clust_data已经是一个具有正确形状的列表列表,并且cellText在填充之后将是相同的clust_data.
此外,尽量不要混合matplotlib的OO和pyplot接口.
以下代码应与您的代码等效
fig=plt.figure()
ax = fig.add_subplot(111)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
colLabels=("Structure", "Energy", "Density")
the_table = ax.table(cellText=clust_data,
colLabels=colLabels,
loc='center')
plt.savefig("table.png")
Run Code Online (Sandbox Code Playgroud)
你必须隐藏轴刺(例如将它们的颜色设置为白色)并将它们放低,zorder然后将表添加到更高的位置zorder
colLabels=("Structure", "Energy", "Density")
nrows, ncols = len(clust_data)+1, len(colLabels)
hcell, wcell = 0.3, 1.
hpad, wpad = 0, 0
fig=plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad))
ax = fig.add_subplot(111)
#remove axis ticks and labels
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
#hide the spines
for sp in ax.spines.itervalues():
sp.set_color('w')
sp.set_zorder(0)
#do the table
the_table = ax.table(cellText=clust_data,
colLabels=colLabels,
loc='center')
#put the table in front of the axes spines
#for some reason zorder is not a keyword in ax.table
the_table.set_zorder(10)
plt.savefig("table.png")
Run Code Online (Sandbox Code Playgroud)
只需关闭轴即可
colLabels=("Structure", "Energy", "Density")
nrows, ncols = len(clust_data)+1, len(colLabels)
hcell, wcell = 0.3, 1.
hpad, wpad = 0, 0
fig=plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad))
ax = fig.add_subplot(111)
ax.axis('off')
#do the table
the_table = ax.table(cellText=clust_data,
colLabels=colLabels,
loc='center')
plt.savefig("table.png")
Run Code Online (Sandbox Code Playgroud)
这只是一种好奇心.你可以用乳胶打印你的桌子.如果您尝试此代码,
import matplotlib.pyplot as plt
import numpy as np
table = r'\begin{table} \begin{tabular}{|l|l|l|} \hline $\alpha$ & $\beta$ & $\gamma$ \\ \hline 32 & $\alpha$ & 123 \\ \hline 200 & 321 & 50 \\ \hline \end{tabular} \end{table}'
plt.plot(np.arange(100))
plt.text(10,80,table, size=50)
plt.show()
Run Code Online (Sandbox Code Playgroud)
你会在情节的左上角看到一张美丽的桌子.现在,编写一个将数据转换为字符串的函数几乎是直截了当的.