Python Seaborn Chart - Shadow Area

左心房为你撑大大i 提交于 2020-07-21 19:04:01

问题


Sorry to my noob question, but how can I add a shadow area/color between the upper and lower lines in a seaborn chart?

The primary code I've working on is the following:

plt.figure(figsize=(18,10))
sns.set(style="darkgrid")
palette = sns.color_palette("mako_r", 3)
sns.lineplot(x="Date", y="Value",  hue='Std_Type', style='Value_Type', sizes=(.25, 2.5), palette = palette, data=tbl4)

The idea is to get some effect like below (the example from seaborn website): But I could not replicate the effect although my data structure is pretty much in the same fashion as fmri (seaborn example)

from seaborn link:

 import seaborn as sns
 sns.set(style="darkgrid")

 # Load an example dataset with long-form data
 fmri = sns.load_dataset("fmri")

 # Plot the responses for different events and regions
 sns.lineplot(x="timepoint", y="signal",
         hue="region", style="event",
         data=fmri)

Do you have some ideas? I tried to change the chart style, but if I go to a distplot or relplot, for example, the x_axis cannot show the timeframe...


回答1:


Check this code:

# import
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
sns.set(style = 'darkgrid')

# data generation
time = pd.date_range(start = '2006-01-01', end = '2020-01-01', freq = 'M')
tbl4 = pd.DataFrame({'Date': time,
                     'down': 1 - 0.5*np.random.randn(len(time)),
                     'up': 4 + 0.5*np.random.randn(len(time))})

tbl4 = tbl4.melt(id_vars = 'Date',
                 value_vars = ['down', 'up'],
                 var_name = 'Std_Type',
                 value_name = 'Value')

# figure plot
fig, ax = plt.subplots(figsize=(18,10))

sns.lineplot(ax = ax,
             x = 'Date',
             y = 'Value',
             hue = 'Std_Type',
             data = tbl4)

# fill area
plt.fill_between(x = tbl4[tbl4['Std_Type'] == 'down']['Date'],
                 y1 = tbl4[tbl4['Std_Type'] == 'down']['Value'],
                 y2 = tbl4[tbl4['Std_Type'] == 'up']['Value'],
                 alpha = 0.3,
                 facecolor = 'green')

plt.show()

which gives me this plot:

Since I do not have access to your data, I generated random ones. Replace them with yours.
The shadow area is done with plt.fill_between (documentation here), where you specify the x array (common to both curves), the upper and lower limits of the area as y1 and y2 and, optionally a color and its transparency with the facecolor and alpha parameters respectively.


You cannot do it through ci parameter, since it is used to show the confidence interval of your data.



来源:https://stackoverflow.com/questions/62649553/python-seaborn-chart-shadow-area

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