2016-04-24 3960 views
4

我想根據列chrom具有特定值的次數來設置條形圖上每個欄的寬度。 我設置寬度的條是出現一個列表:如何在seaborn barplot上設置寬度

list_counts = plot_data.groupby('chrom')['gene'].count() 

widthbars = list_counts.tolist() 

繪製barplot爲:

ax = sns.barplot(x = plot_data['chrom'], y = plot_data['dummy'], width=widthbars) 

這給了我一個錯誤:

TypeError: bar() got multiple values for keyword argument 'width' 

是寬度可變之中隱式設置某處? 如何讓每個小節的寬度不同?

回答

4

雖然在seaborn中沒有內置的方法來執行此操作,但您可以操作sns.barplot在matplotlib軸對象上創建的修補程序。

下面是基於seaborn example for barplot here的最基本的示例。

請注意,每個小柱被分配一個寬度爲1個單位的空間,所以重要的是將您的計數標準化爲區間0-1。

import matplotlib.pyplot as plt 
import seaborn as sns 

sns.set_style("whitegrid") 
tips = sns.load_dataset("tips") 
ax = sns.barplot(x="day", y="total_bill", data=tips) 

# Set these based on your column counts 
columncounts = [20,40,60,80] 

# Maximum bar width is 1. Normalise counts to be in the interval 0-1. Need to supply a maximum possible count here as maxwidth 
def normaliseCounts(widths,maxwidth): 
    widths = np.array(widths)/float(maxwidth) 
    return widths 

widthbars = normaliseCounts(columncounts,100) 

# Loop over the bars, and adjust the width (and position, to keep the bar centred) 
for bar,newwidth in zip(ax.patches,widthbars): 
    x = bar.get_x() 
    width = bar.get_width() 
    centre = x+width/2. 

    bar.set_x(centre-newwidth/2.) 
    bar.set_width(newwidth) 

plt.show() 

enter image description here

+1

尼斯。因爲問題是關於使用寬度的計數度量,所以我會提到每個小節分配一個寬度爲1個單位的空間,所以最好在寬度測量中添加某種標準化,否則將會是圖形無法解釋。 – mwaskom

+1

感謝您的建議。我認爲我的編輯也涵蓋了這一點 – tom