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

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

问题描述

我正在尝试Seaborn,以使我的绘图在视觉上比matplotlib更好.我有一个数据集,其中有一个年"列,我想在X轴上绘制,并在Y轴上使用不同的彩色线绘制4列,分别是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从其宽格式"(每种度量类型一列)转换为长格式(所有度量值一列,用于指示类型的一列)的关键要素是

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']))

(请注意,值"和变量"是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天全站免登陆