Colorize the background of a seaborn plot using a column in dataframe

眉间皱痕 提交于 2020-08-02 07:40:52

问题


Question

How to shade or colorize the background of a seaborn plot using a column of a dataframe?

Code snippet

import numpy as np
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
fmri = sns.load_dataset("fmri")
fmri.sort_values('timepoint',inplace=True)
ax = sns.lineplot(x="timepoint", y="signal", data=fmri)
arr = np.ones(len(fmri))
arr[:300] = 0
arr[600:] = 2
fmri['background'] = arr

ax = sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri)

Which produced this graph:

Desired output

What I'd like to have, according to the value in the new column 'background' and any palette or user defined colors, something like this:


回答1:


ax.axvspan() could work for you, assuming backgrounds don't overlap over timepoints.

import numpy as np
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
fmri = sns.load_dataset("fmri")
fmri.sort_values('timepoint',inplace=True)
arr = np.ones(len(fmri))
arr[:300] = 0
arr[600:] = 2
fmri['background'] = arr
fmri['background'] = fmri['background'].astype(int).astype(str).map(lambda x: 'C'+x)

ax = sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri)
ranges = fmri.groupby('background')['timepoint'].agg(['min', 'max'])
for i, row in ranges.iterrows():
    ax.axvspan(xmin=row['min'], xmax=row['max'], facecolor=i, alpha=0.3)



来源:https://stackoverflow.com/questions/60887648/colorize-the-background-of-a-seaborn-plot-using-a-column-in-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!