2016-07-12 13 views
2

我只是想繪製幾個數據集,說4,採用子圖,即像如何在Python中爲一個圖形使用多種背景顏色?

fig = figure(1) 
ax1 = fig.add_subplot(221) 
ax2 = fig.add_subplot(222) 
ax3 = fig.add_subplot(223) 
ax4 = fig.add_subplot(224) 

這是運作良好。但另外我想爲第一行中的兩個子圖和第二行中的兩個子圖設置不同的背景顏色,使得圖的背景上半部分是黑色,下半部分是白色。 有人可以告訴我如何做到這一點?

那麼,我到目前爲止所嘗試的是定義兩個數字,一個用黑色,另一個用白色背景將前兩個子圖添加到圖1,其他圖則添加到圖2.最後,我合併了兩個數字轉換成PDF格式,但結果並不令人滿意,因爲PDF文件亂七八糟,這兩個數字實際上看起來像兩個不同的數字,但不像一個數字。

此外,我想是這樣

fig = figure(1) 
rect = fig.patch 
rect.set_facecolor('black') 
ax1 = fig.add_subplot(221) 
ax2 = fig.add_subplot(222) 
rect = fig.patch 
rect.set_facecolor('white') 
ax3 = fig.add_subplot(223) 
ax4 = fig.add_subplot(224) 

但顯然它不能像這樣工作。然後我嘗試使用matplotlib.patches爲每個子圖創建一個矩形作爲背景,這似乎也不合適。

+0

你可能包括到目前爲止你已經嘗試了什麼? – sawreals

+0

可能的副本[設置背景顏色的子圖](http://stackoverflow.com/questions/23313586/set-background-color-for-subplot) – albert

+0

正如我通過改變子圖的背景顏色理解,我改變顏色的繪圖區域,但我想更改畫布的顏色。 – berti

回答

1

我有同樣的問題,並與下面的解決方案上來:

import matplotlib.pyplot as plt 
import matplotlib.patches as patches 

fig = plt.figure(1) 

# create rectangles for the background 
upper_bg = patches.Rectangle((0, 0.5), width=1, height=0.5, 
          transform=fig.transFigure,  # use figure coordinates 
          facecolor='gray',    # define color 
          edgecolor='none',    # remove edges 
          zorder=0)      # send it to the background 
lower_bg = patches.Rectangle((0, 0), width=1.0, height=0.5, 
          transform=fig.transFigure,  # use figure coordinates 
          facecolor='white',    # define color 
          edgecolor='none',    # remove edges 
          zorder=0)      # send it to the background 

# add rectangles to the figure 
fig.patches.extend([upper_bg, lower_bg]) 

# create subplots as usual 
fig.add_subplot(221) 
fig.add_subplot(222) 
fig.add_subplot(223) 
fig.add_subplot(224) 

plt.show() 

請注意,你必須明確地設置zorder,因爲否則的補丁都在次要情節的前面。由此得出的數字如下所示:

Resulting figure with two different background colors 這種方法仍然依賴於matplotlib.patches,因此可能不是你要找的乾淨的,但我認爲這可能是有這個問題別人有用。在操縱數字本身

更多信息可以在這裏找到:http://matplotlib.org/users/artists.html#figure-container

相關問題