天天看點

python怎麼在畫布上寫字_matplotlib-直接在畫布上繪制

由于動态更新的性能問題,我需要在畫布上直接繪制很多矩形作為非常低的級别,也就是說,不使用matplotlib.patches,就像我們必須使用經典的GUI一樣。

更準确地說,我隻想畫一個矩形,而不是所有的圖形。

有可能嗎?

這是我使用Joe Kington給出的連結的測試代碼。#!/usr/bin/env python3

from random import randint, choice

import time

import matplotlib.pyplot as plt

import matplotlib.patches as mpatches

import matplotlib.colors as colors

import matplotlib

back_color = "black"

colors = ['red', 'green', 'cyan', 'yellow']

width = 16

height = 16

ax = plt.subplot(111)

canvas = ax.figure.canvas

ax.set_xlim([0, width])

ax.set_ylim([0, height])

def update():

global ax, canvas, colors, width, height

x = randint(0, width - 1)

y = randint(0, height - 1)

rect = mpatches.Rectangle(

(x, y), 1, 1,

facecolor = choice(colors),

edgecolor = back_color

)

start = time.time()

ax.draw_artist(rect)

canvas.blit(ax.bbox)

print("draw >>>", time.time() - start)

timer = canvas.new_timer(interval = 1)

timer.add_callback(update)

timer.start()

plt.show()

在Mac O$下,我獲得以下消息。Traceback (most recent call last):

File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/backend_bases.py", line 1203, in _on_timer

ret = func(*args, **kwargs)

File "/Users/xxx/test.py", line 86, in update

ax.draw_artist(rect)

File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/axes.py", line 2100, in draw_artist

a.draw(self._cachedRenderer)

File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/artist.py", line 56, in draw_wrapper

draw(artist, renderer, *args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/patches.py", line 393, in draw

gc = renderer.new_gc()

File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/matplotlib/backends/backend_macosx.py", line 97, in new_gc

self.gc.save()

RuntimeError: CGContextRef is NULL

對于特立獨行的使用者

我有一個好消息給Mac使用者誰想玩以下代碼,也與動畫。我在沒有任何軟體的Mac上重新安裝了Maverick作業系統,這稱為幹淨安裝,然後我安裝了Anaconda和XQuark(see this)。

要使動畫工作,隻需在導入任何其他matplotlib之前使用以下兩行即可。import matplotlib

matplotlib.use('TkAgg')

我認為這将适用于任何由Anaconda支援的Mac作業系統。XQuark的使用隻對Maverick是必需的。