2014-02-24 20 views
2

我目前正在繪製相同的數據,但兩個次要情節不同的可視化它(見圖): Scatter and horizontal bar plot一個傳說中pyplot所有次要情節

的代碼片段用於生產如上圖所示:

# Figure 
plt.figure(figsize=(14,8), dpi=72) 
plt.gcf().suptitle(r'Difference between TI and $\lambda$D', size=16) 
# Subplot 1 
ax1 = plt.subplot2grid((1,3),(0,0),colspan=2) 

# Plot scattered data in first subplot 
plt.scatter(LE_x, LE_y, s=40, lw=0, color='gold', marker='o', label=r'$\lambda$D') 
plt.scatter(MD_x, MD_y, s=40, lw=0, color='blue', marker='^', label=r'TI') 

# Subplot 2 
ax2 = plt.subplot2grid((1,3),(0,2)) 

plt.barh(vpos1, LE_hist, height=4, color='gold', label=r'$\lambda$D') 
plt.barh(vpos2, MD_hist, height=4, color='blue', label=r'TI') 

# Legend 
legend = plt.legend() 

有沒有什麼辦法讓圖例同時顯示散點和條?這是否也會按照here描述的每個假人去?那麼有人可以爲此發佈一個最簡單的工作示例,因爲我無法繞過這個環節。

回答

4

這對我來說很有用,你基本上捕獲了繪製的每個圖形的補丁句柄,並在最後手動創建圖例。

import pylab as plt 
import numpy as NP 

plt.figure(figsize=(14,8), dpi=72) 
plt.gcf().suptitle(r'Difference between TI and $\lambda$D', size=16) 
# Subplot 1 
ax1 = plt.subplot2grid((1,3),(0,0),colspan=2) 
N = 100 
LE_x = NP.random.rand(N) 
LE_y = NP.random.rand(N) 
MD_x = NP.random.rand(N) 
MD_y = NP.random.rand(N) 

# Plot scattered data in first subplot 
s1 = plt.scatter(LE_x, LE_y, s=40, lw=0, color='gold', marker='o', label=r'$\lambda$D') 
s2 = plt.scatter(MD_x, MD_y, s=40, lw=0, color='blue', marker='^', label=r'TI') 

data = NP.random.randn(1000) 
LE_hist, bins2 = NP.histogram(data, 50) 

data = NP.random.randn(1000) 
MD_hist, bins2 = NP.histogram(data, 50) 
# Subplot 2 
ax2 = plt.subplot2grid((1,3),(0,2)) 
vpos1 = NP.arange(0, len(LE_hist)) 
vpos2 = NP.arange(0, len(MD_hist)) + 0.5 
h1 = plt.barh(vpos1, LE_hist, height=0.5, color='gold', label=r'$\lambda$D') 
h2 = plt.barh(vpos2, MD_hist, height=0.5, color='blue', label=r'TI') 

# Legend 
#legend = plt.legend() 
lgd = plt.legend((s1, s2, h1, h2), (r'$\lambda$D', r'TI', r'$\lambda$D', r'TI'), loc='upper center') 
plt.show() 

Result

+0

如此美麗,如此優雅!我猜這可能不是一種簡單的方法,只顯示一行中的標籤和兩個符號的兩倍? – tschoppi

+1

@tschoppi:你可以通過使圖例有兩列來作弊,使兩個標籤空白並減小列間距:'lgd = plt.legend((s1,s2,h1,h2),(r「 ,r'',r'$ \ lambda $ D',r'TI'),ncol = 2,loc ='upper center',columnspacing = 0) – GWW