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?
JavaScript
x
26
26
1
ydata=[1000,250,3000,500,3200,4000,2000]
2
xlabels=['first','sec','third','fourth','fifth','sixth','seventh']
3
4
barwidth = 0.45
5
6
import matplotlib.pyplot as plt
7
8
def create_bar_plot(entries):
9
assert entries > 0
10
xdata = range(entries)
11
xlabels=xlabels[:entries]
12
xdata=xdata[:entries]
13
ydata=ydata[:entries]
14
figure = plt.figure(figsize = (12,6), facecolor = "white")
15
ax = figure.add_subplot(1,1,1)
16
plt.grid(True)
17
if xdata and ydata:
18
ax.bar(xdata, ydata, width=barwidth,align='center',color='blue')
19
ax.set_xlabel('categories',color='black')
20
ax.set_ylabel('duration in minutes',color='black')
21
ax.set_title('duration plot created ')
22
ax.set_xticks(xdata)
23
ax.set_xticklabels(xlabels)
24
figure.autofmt_xdate(rotation=30)
25
plt.show()
26
When I tried
JavaScript
1
2
1
create_bar_plot(5)
2
I got this figure
But when I called
JavaScript
1
2
1
create_bar_plot(1)
2
I get this fat bar
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..
Please help
Advertisement
Answer
They are actually the same bar width, it’s just your x-axis scale that is different. See:
JavaScript
1
10
10
1
>>> create_bar_plot(5)
2
>>> plt.gca().get_xbound()
3
(-1.0, 5.0)
4
>>> create_bar_plot(1)
5
>>> plt.gca().get_xbound()
6
(-0.30000000000000004, 0.30000000000000004)
7
>>> ax = plt.gca()
8
>>> ax.set_xbound(-1.0 ,5.0)
9
>>> plt.show()
10