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.
CodePudding user response:
You can set Elevation
as index and use
Reason it was not working:
There were two problems:
-
To avoid playing with
height
, what you do is use integers (e.g.,range(len(EleRegion))
asy
and set theyticks
to the correct numbers. This way, the defaultheight
would have worked.- Another issue is that the second bar chart created by using
Axes.barh
requires theleft
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 useDataFrame.plot.barh
to handle all this automatically. - Another issue is that the second bar chart created by using