如何在matplotlib表中设置列的背景色 [英] How to set background color of a column in a matplotlib table
问题描述
我在一个目录中有多个 .txt 文件,例如 d:\memdump\0.txt,1.txt,...10.txt 示例文本文件如下:
应用程序内存使用率(kB):正常运行时间:7857410实时时间:7857410** pid 23875 [com.example.twolibs] 中的 MEMINFO **共享私有堆 堆 堆Pss 脏脏大小分配免费------ ------ ------ ------ ------ ------ ------本机 0 0 0 13504 10836 459达尔维克6806 7740 6580 24076 18523 5553堆栈 80 0 80光标0 0 0阿什姆 0 0 0其他开发人员 14741 836 1028.so mmap 1367 448 1028.jar mmap 0 0 0.apk mmap 225 0 0.ttf mmap 0 0 0.dex mmap 1225 340 16其他mmap 5 8 4未知3473 564 3432总计 27922 9936 12168 37580 29359 6012对象浏览次数:62 ViewRootImpl:2AppContexts:5活动:2资产:3 资产管理器:3本地绑定器:9 代理绑定器:18死亡收件人:0OpenSSL套接字:0的SQLMEMORY_USED:0PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
我必须解析这些文件以获取PID值,本机堆大小,本机堆Alloc大小,Dalvik堆大小,Dalvik堆Alloc大小,并绘制具有以下堆大小的图形
我正在使用以下代码来实现这一目标:
import glob导入操作系统汇入将numpy导入为np导入matplotlib.pyplot作为pltos.chdir("D:\ Python_Trainings \ MemInfo \ Data")pid_arr = []native_heapsize_arr = []dalvik_heapsize_arr = []native_heapalloc_arr = []dalvik_heapalloc_arr = []pkg_name_arr = []#解析内存转储文件的方法def parse_dumpFiles():对于glob.glob("*.txt")中的data_file:尝试:fo = 打开(数据文件,r")对于线在 fo:pid_match = re.search('pid\s+(\d+)',line)pkg_name_match = re.search("\[(\w+\.+\w+\.+\w+)\]",line)native_heapsize_match = re.search('(Native+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)dalvik_heapsize_match = re.search('(Dalvik+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)native_heapalloc_match = re.search('(本机+ \ s + \ d + \ s + \ d + \ s + \ d + \ s + \ d + \ s +)+(\ d +)',行)dalvik_heapalloc_match = re.search('(Dalvik+\s+\d+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)如果pid_match:pid_arr.append(int(pid_match.group(1)))如果 native_heapsize_match:native_heapsize_arr.append(native_heapsize_match.group(2))如果dalvik_heapsize_match:dalvik_heapsize_arr.append(dalvik_heapsize_match.group(2))如果 native_heapalloc_match:native_heapalloc_arr.append(native_heapalloc_match.group(2))如果 dalvik_heapalloc_match:dalvik_heapalloc_arr.append(dalvik_heapalloc_match.group(2))如果 pkg_name_match:如果 pkg_name_match.group(1) 不在 pkg_name_arr 中:pkg_name_arr.append(pkg_name_match.group(1))除了 IOError:打印错误:找不到文件或读取数据"最后:关闭()#end of parse_dumpFiles()方法#从内存转储绘图的方法def plt_MemDump(pid_arr, native_heapsize_arr, dalvik_heapsize_arr, native_heapalloc_arr, dalvik_heapalloc_arr, pkg_name_arr):#创建一个图形和带有表空间的轴无花果= plt.figure()ax = plt.axes([0.2, 0.2, 0.7, 0.7])#将行和列的标签创建为元组colLabels = ('0','10', '20', '30', '40', '50', '60', '70', '80', '90', '100')rowLabels = ('Native Heap Size','Native Heap Allocated','Dalvik Heap Size','Dalvik Heap Allocated','PID')#将表格数据作为numpy数组tableData = np.asarray([native_heapsize_arr,dalvik_heapsize_arr,native_heapalloc_arr,dalvik_heapalloc_arr,pid_arr],dtype = int)#将当前颜色周期作为列表获取,然后将颜色周期重置为开始颜色 = []为真:colors.append(ax._get_lines.color_cycle.next())如果colors [0] == colors [-1]并且len(colors)> 1:颜色.pop(-1)休息对于我在xrange(len(colors)-1)中:ax._get_lines.color_cycle.next()#显示表格the_table = plt.table(cellText = tableData,rowLabels = rowLabels,rowColours = colors,colLabels = colLabels,loc ='bottom')#制作一些线图xAxis_val = [0,10,20,30,40,50,60,70,80,90,100]ax.plot(xAxis_val,native_heapsize_arr, linewidth=2.5, marker="o", label="Native Heap Size")ax.plot(xAxis_val,dalvik_heapsize_arr,linewidth = 2.5,marker ="D",label ="Dalvik堆大小")ax.plot(xAxis_val,native_heapalloc_arr,linewidth = 2.5,marker ="^",label =已分配本地堆")ax.plot(xAxis_val,dalvik_heapalloc_arr,linewidth = 2.5,marker ="h",label ="Dalvik堆已分配")#显示图例plt.legend(loc='右上角', fontsize=10)#设置PID与第一个PID不同的列颜色c = the_table.get_celld()[(5,3)]c.set_color('r')i = 0当 i<=10 时:c=the_table.get_celld()[(5,i)]if(c.get_text().get_text()!=((the_table.get_celld()[(5,0)]).get_text().get_text())):c.set_color('r')(the_table.get_celld()[(4,i)]).set_color('r')(the_table.get_celld()[(3,i)]).set_color('r')(the_table.get_celld()[(2,i)]).set_color('r')(the_table.get_celld()[(1,i)]).set_color('r')我+=1#关闭x轴刻度线并显示绘图plt.xticks([])#配置Y轴ylim(0,60000)plt.yticks([10000,20000,30000,40000,50000,60000])plt.grid(真)#设置绘图窗口标题的名称fig.canvas.set_window_title(pkg_name_arr [0] +-内存转储图")#设置图的标题plt.title(pkg_name_arr[0],color='r',fontsize=20)#设置Y标签plt.ylabel('堆大小', fontsize=14, color='r')#显示情节plt.show()#plt_MemDump() 方法结束parse_dumpFiles()plt_MemDump(pid_arr, native_heapsize_arr, dalvik_heapsize_arr, native_heapalloc_arr, dalvik_heapalloc_arr, pkg_name_arr)
现在,我想用一些颜色标记表的列,其中PID值与第一个PID值不同(例如,列30,60& 100).
有人能帮我实现这个目标吗?
matplotlib.pyplot.table
已经为您提供了执行所需功能的工具:
cellColours
(与cellText
形状相同):让你为每个单元格选择颜色colColours
:用作rowColours
,但用于列标题
如果您希望一列中的所有单元格都具有特定颜色,您可以执行以下操作
cellcolours = np.empty_like(tableData, dtype='object')对于我来说,cl在enumerate(colLabels)中:如果 cl >50:cellcolors[:,i] = 'r'
,然后调用 cellColours = cellcolours
来调用 plt.table
(尽管我建议您更改为 ax.table
)./p>
如果您还想要彩色列标题,只需执行上述操作
<小时>如果您希望能够在创建表格后更改单元格,table.get_celld()
返回一个单元格字典,其键是每个单元格位置的元组,例如:
{(0, 0): , # 这些是列标题(0, 1): ,(0,2):< matplotlib.table.Cell at 0x5d75450> ;,(0,3):< matplotlib.table.Cell at 0x5d75610> ;,[...](1, -1): , # 这是一个行标题(1, 0): , # 这是一个单元格(1,1):< matxlotlib.table.Cell at 0x5d74150> ;,(1,2):< matplotlib.table.Cell at 0x5d74290> ;,(1,3):< matplotlib.table.Cell at 0x5d743d0> ;,[...](2, -1): , # 这是一个行标题[...] }
您可以使用元组访问每个单元格,例如
c=table.get_celld()[(1,1)]
您可以使用 c.set_color()
设置单元格颜色,并使用 c.get_text().get_text()
检查单元格中的文本(第一个get_text
返回一个 Text
实例,第二个是其中的字符串)
I have multile .txt files in a directory, say, d:\memdump\0.txt,1.txt,...10.txt sample text file is given below:
Applications Memory Usage (kB):
Uptime: 7857410 Realtime: 7857410
** MEMINFO in pid 23875 [com.example.twolibs] **
Shared Private Heap Heap Heap
Pss Dirty Dirty Size Alloc Free
------ ------ ------ ------ ------ ------
Native 0 0 0 13504 10836 459
Dalvik 6806 7740 6580 24076 18523 5553
Stack 80 0 80
Cursor 0 0 0
Ashmem 0 0 0
Other dev 14741 836 1028
.so mmap 1367 448 1028
.jar mmap 0 0 0
.apk mmap 225 0 0
.ttf mmap 0 0 0
.dex mmap 1225 340 16
Other mmap 5 8 4
Unknown 3473 564 3432
TOTAL 27922 9936 12168 37580 29359 6012
Objects
Views: 62 ViewRootImpl: 2
AppContexts: 5 Activities: 2
Assets: 3 AssetManagers: 3
Local Binders: 9 Proxy Binders: 18
Death Recipients: 0
OpenSSL Sockets: 0
SQL
MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
I have to parse these files to get values of PID, Native Heap Size, Native Heap Alloc size, Dalvik Heap Size, Dalvik Heap Alloc size and plot a graph with these heap sizes as below
I am using the following code to achieve this:
import glob
import os
import re
import numpy as np
import matplotlib.pyplot as plt
os.chdir("D:\Python_Trainings\MemInfo\Data")
pid_arr = []
native_heapsize_arr = []
dalvik_heapsize_arr = []
native_heapalloc_arr = []
dalvik_heapalloc_arr = []
pkg_name_arr = []
#Method to parse the memory dump files
def parse_dumpFiles():
for data_file in glob.glob("*.txt"):
try:
fo = open(data_file,"r")
for line in fo:
pid_match = re.search('pid\s+(\d+)',line)
pkg_name_match = re.search("\[(\w+\.+\w+\.+\w+)\]",line)
native_heapsize_match = re.search('(Native+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)
dalvik_heapsize_match = re.search('(Dalvik+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)
native_heapalloc_match = re.search('(Native+\s+\d+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)
dalvik_heapalloc_match = re.search('(Dalvik+\s+\d+\s+\d+\s+\d+\s+\d+\s+)+(\d+)',line)
if pid_match:
pid_arr.append(int(pid_match.group(1)))
if native_heapsize_match:
native_heapsize_arr.append(native_heapsize_match.group(2))
if dalvik_heapsize_match:
dalvik_heapsize_arr.append(dalvik_heapsize_match.group(2))
if native_heapalloc_match:
native_heapalloc_arr.append(native_heapalloc_match.group(2))
if dalvik_heapalloc_match:
dalvik_heapalloc_arr.append(dalvik_heapalloc_match.group(2))
if pkg_name_match:
if pkg_name_match.group(1) not in pkg_name_arr:
pkg_name_arr.append(pkg_name_match.group(1))
except IOError:
print "Error: can\'t find file or read data"
finally:
fo.close()
#end of parse_dumpFiles() Method
#Method to plot from Memory Dumps
def plt_MemDump(pid_arr, native_heapsize_arr, dalvik_heapsize_arr, native_heapalloc_arr, dalvik_heapalloc_arr, pkg_name_arr):
#Create a figure and axes with room for the table
fig = plt.figure()
ax = plt.axes([0.2, 0.2, 0.7, 0.7])
#Create labels for the rows and columns as tuples
colLabels = ('0','10', '20', '30', '40', '50', '60', '70', '80', '90', '100')
rowLabels = ('Native Heap Size','Native Heap Allocated','Dalvik Heap Size','Dalvik Heap Allocated','PID')
#Table data as a numpy array
tableData = np.asarray([native_heapsize_arr,dalvik_heapsize_arr,native_heapalloc_arr,dalvik_heapalloc_arr,pid_arr],dtype=int)
#Get the current color cycle as a list, then reset the cycle to be at the beginning
colors = []
while True:
colors.append(ax._get_lines.color_cycle.next())
if colors[0] == colors[-1] and len(colors)>1:
colors.pop(-1)
break
for i in xrange(len(colors)-1):
ax._get_lines.color_cycle.next()
#Show the table
the_table = plt.table(cellText=tableData, rowLabels=rowLabels, rowColours=colors, colLabels=colLabels, loc='bottom')
#Make some line plots
xAxis_val = [0,10,20,30,40,50,60,70,80,90,100]
ax.plot(xAxis_val,native_heapsize_arr, linewidth=2.5, marker="o", label="Native Heap Size")
ax.plot(xAxis_val,dalvik_heapsize_arr, linewidth=2.5, marker="D", label="Dalvik Heap Size")
ax.plot(xAxis_val,native_heapalloc_arr, linewidth=2.5, marker="^",label="Native Heap Allocated")
ax.plot(xAxis_val,dalvik_heapalloc_arr, linewidth=2.5, marker="h", label="Dalvik Heap Allocated")
#show legend
plt.legend(loc='upper right', fontsize=10)
#set the column color where PID is different from 1st PID
c=the_table.get_celld()[(5,3)]
c.set_color('r')
i=0
while i<=10:
c=the_table.get_celld()[(5,i)]
if(c.get_text().get_text()!=((the_table.get_celld()[(5,0)]).get_text().get_text())):
c.set_color('r')
(the_table.get_celld()[(4,i)]).set_color('r')
(the_table.get_celld()[(3,i)]).set_color('r')
(the_table.get_celld()[(2,i)]).set_color('r')
(the_table.get_celld()[(1,i)]).set_color('r')
i+=1
#Turn off x-axis ticks and show the plot
plt.xticks([])
#Configure Y axis
plt.ylim(0,60000)
plt.yticks([10000,20000,30000,40000,50000,60000])
plt.grid(True)
#Setting the name of the window title of the plot
fig.canvas.set_window_title(pkg_name_arr[0] + "- Memory Dump Plot")
#Setting the Title of the plot
plt.title(pkg_name_arr[0],color='r',fontsize=20)
#Setting Y Label
plt.ylabel('Heap Size', fontsize=14, color='r')
#show plot
plt.show()
#end of plt_MemDump() Method
parse_dumpFiles()
plt_MemDump(pid_arr, native_heapsize_arr, dalvik_heapsize_arr, native_heapalloc_arr, dalvik_heapalloc_arr, pkg_name_arr)
Now I want to mark the columns of the table with some color where PID value differ with 1st PID value.(eg,column 30,60 & 100).
Can anybody help me to achieve this?
matplotlib.pyplot.table
gives you already the tool to do what you need:
cellColours
(of the same shape ofcellText
): let you chose the colour for each cellcolColours
: works asrowColours
, but for the column headers
If you want all the cells in a column to have a specific colour you can do something like this
cellcolours = np.empty_like(tableData, dtype='object')
for i, cl in enumerate(colLabels):
if cl > 50:
cellcolours[:,i] = 'r'
and then call plt.table
(although I suggest you to change to ax.table
) adding the cellColours=cellcolours
keyword.
If you want also the column headers coloured, just do something like above
If you want to be able to change the cells after you create the table, table.get_celld()
returns a dictionary of cells, whose keys are tuples of the position of each cell, eg:
{(0, 0): <matplotlib.table.Cell at 0x5d750d0>, # these are column headers
(0, 1): <matplotlib.table.Cell at 0x5d75290>,
(0, 2): <matplotlib.table.Cell at 0x5d75450>,
(0, 3): <matplotlib.table.Cell at 0x5d75610>,
[...]
(1, -1): <matplotlib.table.Cell at 0x5d757d0>, # this is a row header
(1, 0): <matplotlib.table.Cell at 0x5a58110>, # this is a cell
(1, 1): <matplotlib.table.Cell at 0x5d74150>,
(1, 2): <matplotlib.table.Cell at 0x5d74290>,
(1, 3): <matplotlib.table.Cell at 0x5d743d0>,
[...]
(2, -1): <matplotlib.table.Cell at 0x5d75990>, # this is a row header
[...] }
You can access each cell using the tuple, e.g.
c=table.get_celld()[(1,1)]
You can set the cell color with c.set_color()
and inspect the text in the cell with c.get_text().get_text()
(the first get_text
returns a Text
instance, the second the string in it)
这篇关于如何在matplotlib表中设置列的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!