我正在尝试使用 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")
它创建了一个像这样的表(我也不完全确定如何通过某些行获取行):
非常感谢任何帮助!
最佳答案
您应该能够通过执行以下操作来解决您的问题:
图形大小(编辑):
- 测量单元格的高度和宽度(例如
hcell=0.3
、wcell=1
) - 获取/了解行数和列数(在您的情况下为
len(clust_data)+1
和 3) 创建尺寸正确的图形(您可能需要一些额外的填充)
fig = plt.figure(figsize=(3*wcell+wpad, nrows*hcell+hpad))
- 测量单元格的高度和宽度(例如
两行内的线条是坐标轴的脊椎。
ax.xaxis.set_visible(False) ax.yaxis.set_visible(False)
只是隐藏轴标签和刻度,而不是轴脊。 你必须隐藏它们或将它们涂成白色
查看下面的完整解决方案
无论如何:在我看来,您正在做很多无用的操作。
从你的代码来看,在我看来 clust_data
已经是一个具有正确形状的列表列表,并且填充后的 cellText
将与 clust_data
.
此外,尽量不要混用 matplotlib 的 OO 和 pyplot 接口(interface)。
下面的代码应该等同于你的
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")
编辑:完整解决方案
曲折的方式
您必须隐藏坐标轴的脊柱(例如将它们的颜色设置为白色)并给它们较低的 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")
简单的方法(信用@JoeKington)
只需关闭轴
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")
关于python - 在 matplotlib 中创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17232683/