在 matplotlib 中显示所有数据集的固定宽度条 [英] displaying fixed width bars for all datasets in matplotlib
问题描述
我有以下数据集.我需要为 1,2 或全部绘制 barchats.当我为单个数据项绘制图表时(例如:xdata=[0]
和ydata=[1000]
, xlabels=['first']
,条形图占据整个绘图区域.如何将条形图的宽度限制为 0.45?
I have the following datasets .I need to plot barchats for say 1,2 or all of them.When I plot the chart for a single data item (eg: xdata=[0]
and ydata=[1000]
, xlabels=['first']
, the bar is sclaed to occupy the whole plot area.How do I restrict the barwidth to be say 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
并没有像我预期的那样工作.. 很可能我遗漏了一些东西..
So, how do I make the plot show each bar with fixed width? It seems the width=barwidth
in bar()
doesn't work as I expected it would.. Very likely I am missing something..
请帮忙
推荐答案
它们实际上是相同的条宽,只是你的 x 轴比例不同.见:
They are actually the same bar width, it's just your x-axis scale that is different. See:
>>> 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()
这篇关于在 matplotlib 中显示所有数据集的固定宽度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!