2016-08-28 145 views
3

對網站來說是全新的,對於Python來說也是新手,所以對幫助和提示表示讚賞。我有一些(x,y)的數據在中心周圍形成幾個幾乎是圓形的曲線。但爲了這個例子,我創建了一些(x,y)形成圓。根據函數繪製PatchCollection

現在,我想要繪製這些圖形,並根據顏色填充這些多邊形之間的空間,讓我們說一些函數獲得的(z)值,以便每個「圓環」都有它自己的陰影。

這是,我現在想通了。

import matplotlib.pyplot as plt 
import numpy as np 
from math import sin, cos 
from matplotlib.patches import Polygon 
from matplotlib.collections import PatchCollection 

r = np.array([0.1, 0.2, 0.3, 0.4, 0.5 ,0.6, 0.7, 0.8, 0.9, 1.0]) 

fig, ax = plt.subplots(1) 
ax.set_xlim([-1.1, 1.1]) 
ax.set_ylim([-1.1, 1.1]) 

x=[] 
y=[] 
patches = [] 
colors=np.array([0.9,0.8, 0.1, 0.1, 0.1, 0.4, 0.2,0.8,0.1, 0.9]) 




for radius in r: 
    for phi in np.linspace(0, 360, 200, endpoint=True): 
     x.append(radius*cos(np.deg2rad(phi))) 
     y.append(radius*sin(np.deg2rad(phi))) 
    points = np.vstack([x,y]).T 
    polygon = Polygon(points,False) 
    patches.append(polygon) 

p = PatchCollection(patches, cmap="Blues") 
p.set_array(colors) 

ax.add_collection(p) 

plt.show() 

給予我:rings

  1. 我不知道爲什麼會出現在右邊這個水平線上,這讓我相信,我不明白我的代碼做什麼。
  2. 它並沒有做到這一點,因爲所有的環段具有相同的顏色,而不是具有不同的色調。

我認爲 p.set_array(顏色) 會做的伎倆,因爲我發現它在example 即使我不知道set_array()確實如文檔 不給走了很多。

如果有完全不同的方法,請隨時告訴我。

回答

1

您需要添加從最大到最小的圓圈,以便它們不會互相碰撞。

我用plot a circle with pyplothttp://matplotlib.org/users/colormaps.html

import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.cm as cm 

r = np.arange(1, 0, -0.1) 

fig, ax = plt.subplots(1) 
ax.set_xlim([-1.1, 1.1]) 
ax.set_ylim([-1.1, 1.1]) 

color_vec = np.array([0.9, 0.8, 0.1, 0.1, 0.1, 0.4, 0.2, 0.8, 0.1, 0.9]) 
colors = cm.get_cmap("Blues")(color_vec) 

for i, radius in enumerate(r): 
    circle = plt.Circle((0, 0), radius, color=colors[i]) 
    ax.add_artist(circle) 

plt.show() 

,如果你需要的補丁:

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

r = np.arange(1, 0, -0.1) 

fig, ax = plt.subplots(1) 
ax.set_xlim([-1.1, 1.1]) 
ax.set_ylim([-1.1, 1.1]) 
patches = [] 

colors = np.array([0.9, 0.8, 0.1, 0.1, 0.1, 0.4, 0.2, 0.8, 0.1, 0.9]) 

phi = np.linspace(0, 2*np.pi, 200) 
for radius in r: 
    x = radius * np.cos(phi) 
    y = radius * np.sin(phi) 
    points = np.vstack([x, y]).T 
    polygon = Polygon(points, False) 
    patches.append(polygon) 

p = PatchCollection(patches, cmap="Blues") 
p.set_array(colors) 

ax.add_collection(p) 

plt.show() 
+0

是的,我需要的補丁,我終於想通了,自己說是重疊的問題。但是,如果我只是通過r = r [:: - 1]在我自己的代碼中反轉半徑數組,它不適用於我,即使它在技術上應該與您在那裏做的一樣。如何確定PatchCollection中繪圖的順序(我已經發現zorder單個補丁) – Marsl