📜  如何在 Seaborn 中创建堆积条形图?

📅  最后修改于: 2022-05-13 01:55:28.665000             🧑  作者: Mango

如何在 Seaborn 中创建堆积条形图?

在本文中,我们将讨论如何使用Python在 Seaborn 中创建堆积条形图。

堆积条形图是一种条形图,其中每个条形在视觉上分为子条形,以一次表示多列数据。要绘制堆积条形图,我们需要在 plot 方法中指定stacked=True。我们还可以传递颜色列表,因为我们需要为条形图中的每个子条着色。

句法:

示例:堆积条形图

正在使用的数据集:

 

High Temp

Low Temp

Avg Temp

Jan

28

22

25

Feb

30

26

28

Mar

34

30

32

Apr

38

32

35

May

45

41

43

Jun

42

38

40

Jul

38

32

35

Aug

35

31

33

Sep

32

28

30

Oct

28

22

25

Nov

25

15

20

Dec

21

15

18

Python3
# import necessary libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
 
# create DataFrame
df = pd.DataFrame({'High Temp': [28, 30, 34, 38, 45, 42,
                                 38, 35, 32, 28, 25, 21],
                   'Low Temp': [22, 26, 30, 32, 41, 38,
                                32, 31, 28, 22, 15, 15],
                   'Avg Temp': [25, 28, 32, 35, 43, 40,
                                35, 33, 30, 25, 20, 18]},
                  index=['Jan', 'Feb', 'Mar', 'Apr', 'May',
                         'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
                         'Nov', 'Dec'])
 
 
# create stacked bar chart for monthly temperatures
df.plot(kind='bar', stacked=True, color=['red', 'skyblue', 'green'])
 
# labels for x & y axis
plt.xlabel('Months')
plt.ylabel('Temp ranges in Degree Celsius')
 
# title of plot
plt.title('Monthly Temperatures in a year')


Python3
# import necessary libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
 
# create DataFrame
students = pd.DataFrame({'Boys': [67, 78],
                         'Girls': [72, 80], },
                        index=['First Year', 'Second Year'])
 
 
# create stacked bar chart for students DataFrame
students.plot(kind='bar', stacked=True, color=['red', 'pink'])
 
# Add Title and Labels
plt.title('Intermediate Students Pass %')
plt.xlabel('Year')
plt.ylabel('Percentage Ranges')


输出:

示例:堆积条形图

正在使用的数据集:

 

Boys

Girls

First Year

67

72

Second Year

78

80

Python3

# import necessary libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
 
# create DataFrame
students = pd.DataFrame({'Boys': [67, 78],
                         'Girls': [72, 80], },
                        index=['First Year', 'Second Year'])
 
 
# create stacked bar chart for students DataFrame
students.plot(kind='bar', stacked=True, color=['red', 'pink'])
 
# Add Title and Labels
plt.title('Intermediate Students Pass %')
plt.xlabel('Year')
plt.ylabel('Percentage Ranges')

输出