如何在Seaborn中创建一个区域图(附实例)

336 阅读1分钟

你可以使用以下基本语法在seaborn中创建一个区域图:

import matplotlib.pyplot as plt
import seaborn as sns

#set seaborn style
sns.set_theme()

#create seaborn area chart
plt.stackplot(df.x, df.y1, df.y2, df.y3)

下面的例子展示了如何在实践中使用这种语法。

例1:在Seaborn中创建基本面积图

下面的代码显示了如何在seaborn中创建一个基本的面积图:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

#set seaborn style
sns.set_theme()
 
#define DataFrame
df = pd.DataFrame({'period': [1, 2, 3, 4, 5, 6, 7, 8],
                   'team_A': [20, 12, 15, 14, 19, 23, 25, 29],
                   'team_B': [5, 7, 7, 9, 12, 9, 9, 4],
                   'team_C': [11, 8, 10, 6, 6, 5, 9, 12]})

#create area chart
plt.stackplot(df.period, df.team_A, df.team_B, df.team_C)

X轴显示的是周期变量,Y轴显示的是三个团队在一段时间内的数值。

例2:在Seaborn中创建自定义面积图

下面的代码显示了如何修改区域图的颜色,并添加一个带有特定标签的图例:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

#set seaborn style
sns.set_theme()
 
#define DataFrame
df = pd.DataFrame({'period': [1, 2, 3, 4, 5, 6, 7, 8],
                   'team_A': [20, 12, 15, 14, 19, 23, 25, 29],
                   'team_B': [5, 7, 7, 9, 12, 9, 9, 4],
                   'team_C': [11, 8, 10, 6, 6, 5, 9, 12]})

#define colors to use in chart
color_map = ['red', 'steelblue', 'pink']
    
#create area chart
plt.stackplot(df.period, df.team_A, df.team_B, df.team_C,
              labels=['Team A', 'Team B', 'Team C'],
              colors=color_map)

#add legend
plt.legend(loc='upper left')

#add axis labels
plt.xlabel('Period')
plt.ylabel('Points Scored')

#display area chart
plt.show()

请注意,颜色参数接受颜色名称和十六进制颜色代码。

其他资源

下面的教程解释了如何在seaborn中创建其他常见的图:

如何在Seaborn中创建时间序列图
如何在Seaborn中创建饼图
如何在Seaborn中创建柱状图