如何使用 seaborn 创建多线图? [英] How do I create a multiline plot using seaborn?

查看:47
本文介绍了如何使用 seaborn 创建多线图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Seaborn 使我的情节在视觉上比 matplotlib 更好.我有一个数据集,它有一个Year"列,我想在 X 轴上绘制它,4 列使用不同颜色的线在 Y 轴上表示 A、B、C、D.我试图使用 sns.lineplot 方法来做到这一点,但它只允许 X 轴上的一个变量和 Y 轴上的一个变量.我试过这样做

I am trying out Seaborn to make my plot visually better than matplotlib. I have a dataset which has a column 'Year' which I want to plot on the X-axis and 4 Columns say A,B,C,D on the Y-axis using different coloured lines. I was trying to do this using the sns.lineplot method but it allows for only one variable on the X-axis and one on the Y-axis. I tried doing this

sns.lineplot(data_preproc['Year'],data_preproc['A'], err_style=None)
sns.lineplot(data_preproc['Year'],data_preproc['B'], err_style=None)
sns.lineplot(data_preproc['Year'],data_preproc['C'], err_style=None)
sns.lineplot(data_preproc['Year'],data_preproc['D'], err_style=None)

但是这样我就不会在图中得到一个图例来显示哪个彩色线对应于什么.我尝试查看文档,但找不到合适的方法来执行此操作.

But this way I don't get a legend in the plot to show which coloured line corresponds to what. I tried checking the documentation but couldn't find a proper way to do this.

推荐答案

Seaborn 倾向于使用长格式"作为输入.将 DataFrame 从其宽格式"(每个测量类型一列)转换为长格式(一列用于所有测量值,一列用于指示类型)的关键因素是 pandas.melt.给定一个像你这样结构的 data_preproc,填充随机值:

Seaborn favors the "long format" as input. The key ingredient to convert your DataFrame from its "wide format" (one column per measurement type) into long format (one column for all measurement values, one column to indicate the type) is pandas.melt. Given a data_preproc structured like yours, filled with random values:

num_rows = 20
years = list(range(1990, 1990 + num_rows))
data_preproc = pd.DataFrame({
    'Year': years, 
    'A': np.random.randn(num_rows).cumsum(),
    'B': np.random.randn(num_rows).cumsum(),
    'C': np.random.randn(num_rows).cumsum(),
    'D': np.random.randn(num_rows).cumsum()})

具有四条线的单个图,每种测量类型一条,通过

A single plot with four lines, one per measurement type, is obtained with

sns.lineplot(x='Year', y='value', hue='variable', 
             data=pd.melt(data_preproc, ['Year']))

(请注意,'value' 和 'variable' 是 melt 返回的默认列名,可以根据自己的喜好进行调整.)

(Note that 'value' and 'variable' are the default column names returned by melt, and can be adapted to your liking.)

这篇关于如何使用 seaborn 创建多线图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆