【问题标题】:displaying fixed width bars for all datasets in matplotlib在 matplotlib 中显示所有数据集的固定宽度条
【发布时间】:2013-01-17 07:10:54
【问题描述】:

我有以下数据集。我需要为 1,2 或全部绘制条形图。当我为单个数据项绘制图表时(例如: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)

我得到了这个数字

但是当我打电话时

create_bar_plot(1)

我得到了这个胖条

那么,如何使绘图以固定宽度显示每个条形?看来bar() 中的width=barwidth 不像我预期的那样工作.. 很可能我错过了一些东西..

请帮忙

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    它们实际上是相同的条宽,只是您的 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()
    

    【讨论】:

      【解决方案2】:

      条形仍然是相同的宽度,0.45,但由于数据较少,x 轴的范围缩小了。您可以手动设置 xlim() 使两个轴的宽度相同,然后条形也将具有相同的宽度。

      所以:

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

      它不会再使条居中,因此您可能需要根据您所追求的最终结果进行进一步调整。

      【讨论】:

        猜你喜欢
        • 2018-02-05
        • 2022-11-22
        • 1970-01-01
        • 1970-01-01
        • 2014-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-09
        相关资源
        最近更新 更多