2015-11-18 25 views
3

使用Matplotlib我想刪除圖中的網格線,同時保留幀(即軸線)。我已經嘗試了下面的代碼和其他選項,但是我無法使其工作。如何在移除網格線時簡單地保留框架?刪除網格線,但保持幀(matplotlib中的ggplot2樣式)

我這樣做是爲了在matplotlib中重現一個ggplot2圖。我已經創建了一個MWE。請注意,你需要一個相對較新版本的matplotlib來使用ggplot2風格。

enter image description here

import matplotlib 
matplotlib.use('Agg') 
import matplotlib.pyplot as plt 
import pylab as P 
import numpy as np 

if __name__ == '__main__': 


    values = np.random.uniform(size=20) 

    plt.style.use('ggplot') 
    fig = plt.figure() 
    _, ax1 = P.subplots()  

    weights = np.ones_like(values)/len(values) 
    plt.hist(values, bins=20, weights=weights) 
    ax1.set_xlabel('Value') 
    ax1.set_ylabel('Probability')  

    ax1.grid(b=False) 
    #ax1.yaxis.grid(False) 
    #ax1.xaxis.grid(False) 

    ax1.set_axis_bgcolor('white')  
    ax1.set_xlim([0,1]) 

    P.savefig('hist.pdf', bbox_inches='tight') 
+1

'AX1。網格(假)'適用於我。你可以粘貼一個它不工作的代碼示例嗎? – kikocorreoso

+0

'ggplot'雖然看起來不像你的例子。並沒有出現任何框架(只是一個灰色的背景)。刪除網格線不會改變這一點。例如,請參閱示例[here](http://matplotlib.org/1.5.0/examples/style_sheets/plot_ggplot.html)。他們都沒有框架。如果你想重現上面的圖片,我會推薦'matplotlib's'的默認樣式,它更接近。 – tom

+0

我想重現一個即。使用ggplot2創建,這就是我從這種風格開始的原因。看到我更新的帖子。 – pir

回答

3

OK,我想這是你所要求的(但糾正我,如果我誤解):

您需要更改spines的顏色。你需要爲每個spine做到這一點單獨使用set_color方法:

for spine in ['left','right','top','bottom']: 
    ax1.spines[spine].set_color('k') 

enter image description here

你可以看到this examplethis example更多有關使用spines。但是,如果你已經刪除了灰色背景和網格線,並添加了刺,這實際上不再是ggplot風格;這真的是你想用的風格嗎?

編輯

爲了使柱狀圖觸摸框的邊緣,你需要:

  1. 更改您的分級,所以垃圾桶邊去0和1

    n,bins,patches = plt.hist(values, bins=np.linspace(0,1,21), weights=weights) 
    # Check, by printing bins: 
    print bins[0], bins[-1] 
    # 0.0, 1.0 
    

    enter image description here

  2. 如果你真的想保持箱values.min()values.max()之間去,你就需要改變你的陰謀限制不再是0和1:

    n,bins,patches = plt.hist(values, bins=20, weights=weights) 
    ax.set_xlim(bins[0],bins[-1]) 
    

enter image description here

+0

好吧,我認爲這比理解所有通過設置ggplot2風格所做的小修改更容易。我無法真正決定風格,我需要它匹配來自ggplot2的相同的情節,他們在那裏刪除了背景。 – pir

+0

看起來框架在邊緣附近有點偏離? – pir

+0

夠公平的。你能更具體地瞭解「邊緣附近有點不足」的含義嗎? – tom