簡體   English   中英

在 matplotlib 中顯示所有數據集的固定寬度條

[英]displaying fixed width bars for all datasets in matplotlib

我有以下數據集。我需要為 1,2 或全部繪制 barchats。當我為單個數據項繪制圖表時(例如: xdata=[0]ydata=[1000] , xlabels=['first'] ,條形圖占據整個繪圖區域。如何將條形圖的寬度限制為 0.45?

ydata=[1000,250,3000,500,3200,4000,2000]
xlabels=['first','sec','third','fourth','fifth','sixth','seventh']

barwidth = 0.45

import matplotlib.pyplot as plt

def create_bar_plot(entries):
    assert entries > 0    
    xdata = range(entries)
    xlabels=xlabels[:entries]
    xdata=xdata[:entries]
    ydata=ydata[:entries]        
    figure = plt.figure(figsize = (12,6), facecolor = "white")
    ax = figure.add_subplot(1,1,1)
    plt.grid(True)
    if xdata and ydata:
        ax.bar(xdata, ydata, width=barwidth,align='center',color='blue')
        ax.set_xlabel('categories',color='black')
        ax.set_ylabel('duration in  minutes',color='black')
        ax.set_title('duration plot created ')
        ax.set_xticks(xdata)
        ax.set_xticklabels(xlabels)
        figure.autofmt_xdate(rotation=30)
        plt.show()

當我嘗試

create_bar_plot(5)

我得到了這個數字http://i.stack.imgur.com/nhHEM.jpg

但是當我打電話

create_bar_plot(1)

我得到了這個胖棒

http://i.stack.imgur.com/e0IJi.jpg

那么,如何讓繪圖顯示每個條形固定寬度? 似乎bar()中的width=barwidth不像我預期的那樣工作..很可能我遺漏了一些東西..

請幫忙

它們實際上是相同的條寬,只是您的 x 軸比例不同。 看:

>>> create_bar_plot(5)
>>> plt.gca().get_xbound()
(-1.0, 5.0)
>>> create_bar_plot(1)
>>> plt.gca().get_xbound()
(-0.30000000000000004, 0.30000000000000004)
>>> ax = plt.gca()
>>> ax.set_xbound(-1.0 ,5.0)
>>> plt.show()

1

條形仍然是相同的寬度,0.45,但 x 軸的范圍縮小了,因為數據較少。 您可以手動設置 xlim() 以使兩個軸具有相同的寬度,然后條形也將具有相同的寬度。

所以:

    ax.set_xlim(-1,len(xlabels))

它不會再將酒吧居中,因此您可能需要根據您所追求的最終結果進行一些進一步的調整。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM