2017-10-28 116 views
2

我試圖創建一個帶seaborn的直方圖,其中bin從0開始並轉到1.但是,只有在0.22到0.34範圍內的日期。爲了更好地呈現數據,我希望空白空間更具視覺效果。擴展seaborn直方圖中bin的範圍

創建我的片材

import pandas as pd 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
import numpy as np 
import seaborn as sns 

%matplotlib inline 
from IPython.display import set_matplotlib_formats 
set_matplotlib_formats('svg', 'pdf') 

df = pd.read_excel('test.xlsx', sheetname='IvT') 

在這裏,我創建了一個變量爲我的列表和一個我認爲應該定義直方圖的區間範圍內。

st = pd.Series(df['Short total']) 
a = np.arange(0, 1, 15, dtype=None) 

和直方圖本身看起來像這樣

sns.set_style("white") 
plt.figure(figsize=(12,10)) 
plt.xlabel('Ration short/total', fontsize=18) 
plt.title ('CO3 In vitro transcription, Na+', fontsize=22) 

ax = sns.distplot(st, bins=a, kde=False) 

plt.savefig("hist.svg", format="svg") 
plt.show() 

Histogram

它創建了一個圖表位X從0到0.2050和y在-0.04至0.04的範圍內。與我所期望的完全不同。我谷歌搜索相當一段時間,但似乎無法找到我的具體問題的答案。

已經,謝謝你的幫助。

回答

1

這裏有幾種方法可以達到預期的效果。例如,您可以在繪製柱狀圖後更改x軸的極限,或者調整創建柱的範圍。

import seaborn as sns 

# Load sample data and create a column with values in the suitable range 
iris = sns.load_dataset('iris') 
iris['norm_sep_len'] = iris['sepal_length']/(iris['sepal_length'].max()*2) 
sns.distplot(iris['norm_sep_len'], bins=10, kde=False) 

enter image description here

更改x軸限制值(箱仍然在你的數據範圍創建):

ax = sns.distplot(iris['norm_sep_len'], bins=10, kde=False) 
ax.set_xlim(0,1) 

enter image description here

在範圍0到創建箱1:

sns.distplot(iris['norm_sep_len'], bins=10, kde=False, hist_kws={'range':(0,1)}) 

enter image description here

由於對垃圾箱範圍越大,你現在需要的,如果你想擁有同樣的箱的寬度調整XLIM時,作爲使用多個頻段:

sns.distplot(iris['norm_sep_len'], bins=45, kde=False, hist_kws={'range':(0,1)}) 

enter image description here

+0

非常感謝你。那就是訣竅。有沒有辦法,我也可以使用下面的參數來獲得酒吧周圍的邊框? hist_kws = dict(edgecolor =「k」,linewidth = 2) – Jul

+0

@Jul'hist_kws'將參數從matplotlib發送到底層直方圖函數。您可以通過閱讀文檔來查看所有可以傳遞的參數:'import matplotlib.pyplot as plt; ?plt.hist'在這種情況下,您希望將'histt​​ype'指定爲''bar''。不要忘記接受和upvote這個答案它解決了你的問題。 –

+0

如果我將直方圖的代碼更改爲ax = sns.distplot(st,bins = 34,kde = False,color ='#007b7f',histt​​ype ='bar',hist_kws = dict(edgecolor =「k」,linewidth = 2))它給了我一個錯誤消息,說:_distplot()有一個意外的關鍵字參數'histt​​ype'_。或者我必須更改matplotlib中的組織類型? – Jul