如何在Matplotlib中将颜色设置为Rectangle?

Rok*_*lič 20 python matplotlib

如何在matplotlib中将颜色设置为Rectangle?我尝试使用参数颜色,但没有成功.

我有以下代码:

fig=pylab.figure()
ax=fig.add_subplot(111)

pylab.xlim([-400, 400])    
pylab.ylim([-400, 400])
patches = []
polygon = Rectangle((-400, -400), 10, 10, color='y')
patches.append(polygon)

p = PatchCollection(patches, cmap=matplotlib.cm.jet)
ax.add_collection(p)
ax.xaxis.set_major_locator(MultipleLocator(20))    
ax.yaxis.set_major_locator(MultipleLocator(20))    

pylab.show()
Run Code Online (Sandbox Code Playgroud)

fra*_*xel 30

我无法让你的代码工作,但希望这会有所帮助:

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
rect1 = matplotlib.patches.Rectangle((-200,-100), 400, 200, color='yellow')
rect2 = matplotlib.patches.Rectangle((0,150), 300, 20, color='red')
rect3 = matplotlib.patches.Rectangle((-300,-50), 40, 200, color='#0099FF')
circle1 = matplotlib.patches.Circle((-200,-250), radius=90, color='#EB70AA')
ax.add_patch(rect1)
ax.add_patch(rect2)
ax.add_patch(rect3)
ax.add_patch(circle1)
plt.xlim([-400, 400])
plt.ylim([-400, 400])
plt.show()
Run Code Online (Sandbox Code Playgroud)

生产: 在此输入图像描述


sda*_*aau 5

事实证明,你需要做的ax.add_artist(Rectangle)是让颜色规格有效; 使用时patches.append(Rectangle),矩形显示为蓝色(至少在我的电脑上),忽略任何颜色规格.

顺便说一句,请注意艺术家 - Matplotlib 1.2.1文档:类matplotlib.patches.Rectangle说明有

  • edgecolor - 用于笔触颜色
  • facecolor - 填充颜色

...然后有color- 它基本上同时设置笔划和填充颜色.

这是修改后的OP代码,我在Linux(Ubuntu 11.04),python 2.7,matplotlib 0.99.3上测试过:

import matplotlib.pyplot as plt
import matplotlib.collections as collections
import matplotlib.ticker as ticker

import matplotlib
print matplotlib.__version__ # 0.99.3

fig=plt.figure() #pylab.figure()
ax=fig.add_subplot(111)

ax.set_xlim([-400, -380]) #pylab.xlim([-400, 400])
ax.set_ylim([-400, -380]) #pylab.ylim([-400, 400])
patches = []
polygon = plt.Rectangle((-400, -400), 10, 10, color='yellow') #Rectangle((-400, -400), 10, 10, color='y')
patches.append(polygon)

pol2 = plt.Rectangle((-390, -390), 10, 10, facecolor='yellow', edgecolor='violet', linewidth=2.0)
ax.add_artist(pol2)


p = collections.PatchCollection(patches) #, cmap=matplotlib.cm.jet)
ax.add_collection(p)
ax.xaxis.set_major_locator(ticker.MultipleLocator(20)) # (MultipleLocator(20)) 
ax.yaxis.set_major_locator(ticker.MultipleLocator(20)) # (MultipleLocator(20)) 

plt.show() #pylab.show()
Run Code Online (Sandbox Code Playgroud)

这是输出:

matplotlib.png