2014-09-19 38 views
0

我使用matplotlib通过以下方式来生成图像:如何在多边形顶部放置圆?

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.fill(border[0],border[1], color='g', linewidth=1, fill=True, alpha = 0.5) 
patches = [] 
for x1,y1,r in zip(x, y, radii): 
    circle = Circle((x1,y1), r) 
    patches.append(circle) 
p = PatchCollection(patches, cmap='cool', alpha=1.0) 
p.set_array(c) 
ax.add_collection(p) 
plt.colorbar(p) 
plt.savefig(fig_name) 

我想有一个多边形(通过其边界给出)和彩色圆圈这个多边形的顶部。但是,我在圆圈顶部找到了多边形。

这很奇怪,因为我先绘制了多边形,然后向图中添加了圆圈。

有人知道它为什么会发生,以及如何解决这个问题?

ADDED

按照要求,在这里是完全工作的例子:

import pandas 

import matplotlib 
import matplotlib.pyplot as plt 
from matplotlib.collections import PatchCollection 
from matplotlib.patches import Circle, Polygon 
import numpy as np 

def plot_xyc(df, x_col, y_col, c_col, radius, fig_name, title, zrange): 


    resolution = 50 

    x = df[x_col] 
    y = df[y_col] 
    c = df[c_col] 

    x0 = (max(x) + min(x))/2.0 
    y0 = (max(y) + min(y))/2.0 

    dx = (max(x) - min(x)) 
    dy = (max(y) - min(y)) 

    delta = max(dx, dy) 

    radii = [delta*radius for i in range(len(x))] 

    fig = plt.figure() 
    plt.title(title) 

    ax = fig.add_subplot(111) 


    border = ([-3, 3, 3, -3], [-3, -3, 3, 3]) 

    ax.fill(border[0],border[1], color='g', linewidth=1, fill=True, alpha = 1.0) 

    patches = [] 
    for x1,y1,r in zip(x, y, radii): 
     circle = Circle((x1,y1), r) 
     patches.append(circle) 


    patches.append(Circle((-100,-100), r)) 
    patches.append(Circle((-100,-100), r)) 

    p = PatchCollection(patches, cmap='cool', alpha=1.0) 

    p.set_array(c) 
    max_ind = max(c.index) 
    c.set_value(max_ind + 1, min(zrange)) 
    c.set_value(max_ind + 2, max(zrange)) 


    plt.xlim([x0 - delta/2.0 - 0.05*delta, x0 + delta/2.0 + 0.05*delta]) 
    plt.ylim([y0 - delta/2.0 - 0.05*delta, y0 + delta/2.0 + 0.05*delta]) 

    ax.add_collection(p) 


    plt.colorbar(p) 

    plt.savefig(fig_name) 

if __name__ == '__main__': 

    df = pandas.DataFrame({'x':[1,2,3,4], 'y':[4,3,2,1], 'z':[1,1,2,2]}) 

    plot_xyc(df, 'x', 'y', 'z', 0.1, 'test2.png', 'My Titlle', (0.0, 3.0)) 
+0

你能提供一个完整的工作示例吗? – Ffisegydd 2014-09-19 12:10:39

回答

2

您正在寻找zorder

在matplotlib中,所有附加参数只是传递给类的层次结构。 zorderArtist类的kwarg,所以你只需要确保它在某个时候得到zorder

你可以在你的例子中用两种方法做到这一点;

要么将​​其添加在这里:

ax.fill(border[0],border[1], color='g', linewidth=1, fill=True, alpha = 1.0, zorder=1) 

或在这里:

p = PatchCollection(patches, cmap='cool', alpha=1.0, zorder=2) 

,或者如果你想两者兼而有之。 zorder较高的对象位于值较低的对象之上。