Reputation: 241
I try to plot a horizontal stacked bar chart, with elevation as the y axis, and Europe and North America (data) stacked along the x-axis with the following code. Not sure what's wrong. Not all data are shown and the width of the bar is too thin to look at.
fig, ax = plt.subplots()
ax.barh(EleRegion['Elevation'], EleRegion['Europe'], label = 'Europe')
ax.barh(EleRegion['Elevation'], EleRegion['North America'], label ='North America' )
The dataset is below:
0 0
1 100
2 200
3 300
4 400
5 500
6 600
7 700
8 800
9 900
10 1000
11 1100
12 1200
13 1300
14 1400
15 1500
16 1600
17 1700
18 1800
19 1900
20 2000
21 2100
22 2200
23 2300
Name: Elevation, dtype: int64 0 11188
1 9407
2 8801
3 8801
4 8692
5 7563
6 7134
7 6121
8 5077
9 3684
10 3330
11 1084
12 1084
13 918
14 918
15 776
16 776
17 75
18 75d
19 0
20 0
21 0
22 0
23 0
Name: Europe, dtype: int64
0 2657
1 1786
2 1786
3 1786
4 959
5 885
6 564
7 187
8 187
9 0
10 0
11 0
12 0
13 0
14 0
15 0
16 0
17 0
18 0
19 0
20 0
21 0
22 0
23 0
Name: North America, dtype: int64
///repeat to post/// I try to plot a horizontal stacked bar chart, with elevation as the y axis, and Europe and North America (data) stacked along the x-axis with the following code. Not sure what's wrong. Not all data are shown and the width of the bar is too thin to look at.
Upvotes: 1
Views: 133
Reputation: 4407
You can set Elevation
as index and use DataFrame.plot.barh
:
ax = EleRegion.set_index('Elevation').plot.barh(stacked=True)
ax.set_ylabel('Count')
Result:
There were two problems:
Axes.barh
accepts y
, width
and height
. You were passing the first two, but the height was still the default 0.8
. The issue is that your y
axis is in the range of thousands, so the bars were too tiny to be seen. You can set it to 50 and you will see them:ax.barh(EleRegion['Elevation'], EleRegion['Europe'], 50, label = 'Europe')
To avoid playing with height
, what you do is use integers (e.g., range(len(EleRegion))
as y
and set the yticks
to the correct numbers. This way, the default height
would have worked.
Axes.barh
requires the left
parameter to really be "stacked", otherwise the second chart is just rendered on top of the first:f, ax = plt.subplots()
ax.barh(EleRegion['Elevation'], EleRegion['Europe'], 50, label='Europe')
ax.barh(EleRegion['Elevation'], EleRegion['North America'], 50, left=EleRegion['Europe'], label='North America' )
plt.show()
That's why, since your data is already a DataFrame
, it's more convenient to use DataFrame.plot.barh
to handle all this automatically.
Upvotes: 1