简体   繁体   English

如何在 seaborn/matplotlib 中结合线图和图例

[英]How to combine Line PLots & legends in seaborn/matplotlib

I have a dataframe like this我有一个这样的数据框

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

df = pd.DataFrame({'A': [1,2,3,4,5,4,3,2,1],
                   'B': [200,300,400,800,1500,900,450,275,200],
                   'c': ['up','up','down','up','up','down','down','up','down'],
                   'd': ['r','r','r','r','r','r','r','r','r'],
                   })

When I do a line plot with seaborn with the code sns.lineplot(data=df, x='A', y='B',ci=None) .当我使用代码sns.lineplot(data=df, x='A', y='B',ci=None)使用 seaborn 绘制线图时。 I get a plot like below.我得到如下图。

在此处输入图像描述

As you can see, the points have not completely plotted.如您所见,这些点尚未完全绘制。 When I do the plot with the code below当我使用下面的代码进行绘图时

upDF = df.loc[df['c']=='up']
downDF = df.loc[df['c']=='down']
sns.lineplot(data=upDF, x='A', y='B',ci=None, label = 'up');
sns.lineplot(data=downDF, x='A', y='B',ci=None, label = 'down');
plt.legend()

I get a plot like below我得到如下图

在此处输入图像描述

In this plot, all points are plotted, but they are 'disconnected'.在该图中,所有点都被绘制,但它们是“断开的”。 How can I get a plot like below with the points connected & just only one legend (column 'D' or a constant can be used for legend)我怎样才能得到一个像下面这样的图,连接点并且只有一个图例(列“D”或常数可用于图例)

在此处输入图像描述

If I use sns.lineplot on my actual data, I get the graph like below instead of up & down plotted separately.如果我在实际数据上使用sns.lineplot ,我会得到如下图down up

在此处输入图像描述

You can use pure matplotlib.您可以使用纯 matplotlib。 Select the rows after an up as part of the up Series to ensure joining the points.选择 up 之后的行作为 up 系列的一部分,以确保连接点。 For the legend, add a label that starts with an underscore to be skipped:对于图例,添加以要跳过的下划线开头的标签:

import matplotlib.pyplot as plt
m = df['c']=='up'
upDF = df.loc[m|m.shift()]
downDF = df.loc[~m]
ax = plt.subplot()
upDF.plot(x='A', y='B', label='r', ax=ax)
downDF.plot(x='A', y='B', label='_skip', ax=ax)
ax.legend()

output:输出:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM