我正在尝试读取包含线段的XY端点和与该段关联的值的文件,然后绘制由给定值着色的线段。我遇到的问题是可能存在数十万到数百万个线段,当我尝试读取这些较大的文件时,我遇到了内存错误。是否有一种更有效的内存方式?
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import sys
import csv
if len(sys.argv) > 1:
flofile = sys.argv[1]
else:
flofile = "GU3\GU3.flo"
fig = plt.figure()
ax = fig.add_subplot(111)
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0)
scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=jet)
with open(flofile) as FLO:
title = FLO.readline()
limits = [float(tp) for tp in FLO.readline().split()]
FLO.readline()#headers
for line in FLO:
if 'WELLS' in line: break
frac = ([float(tp) for tp in line.split()])
ax.plot([frac[0],frac[2]],[frac[1],frac[3]],color=colorVal)
#ax.plot(*call_list)
scalarMap._A = []
plt.colorbar(scalarMap)
plt.xlim([0,limits[0]])
plt.ylim([0,limits[1]])
plt.show()
此代码适用于小文件。感谢。
答案 0 :(得分:8)
我会调查LineCollection
(doc)。
s = (600,400)
N = 100000
segs = []
colors = []
my_cmap = plt.get_cmap('jet')
for i in range(N):
x1 = random.random() * s[0]
y1 = random.random() * s[1]
x2 = random.random() * s[0]
y2 = random.random() * s[1]
c = random.random()
colors.append(my_cmap(c))
segs.append(((x1, y1), (x2, y2)))
ln_coll = matplotlib.collections.LineCollection(segs, colors=colors)
ax = plt.gca()
ax.add_collection(ln_coll)
ax.set_xlim(0, 600)
ax.set_ylim(0, 400)
plt.draw()
它还将为第一个参数采用numpy数组列表。
答案 1 :(得分:4)
您可能会考虑首先在位图图像上进行绘图,没有内存问题,然后使用matplotlib对绘图/图像进行微调。举个例子:
from PIL import Image
from PIL import ImageDraw
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
s = (500,500)
N = 100000
im = Image.new('RGBA', s, (255,255,255,255))
draw = ImageDraw.Draw(im)
for i in range(N):
x1 = random.random() * s[0]
y1 = random.random() * s[1]
x2 = random.random() * s[0]
y2 = random.random() * s[1]
c = random.random() * 256
draw.line(((x1,y1),(x2,y2)), fill=(0, 255 - int(c), int(c), 255), width=1)
plt.imshow(np.asarray(im), extent=(-1,1,-1,1), aspect='equal', origin='lower')
plt.show()