Seaborn visualized drawing line graph
For time series or other types of continuous variables, it is easier to observe the overall trend of the data using line graphs. Call Seaborn
the relplot
method in the library and set the parameters kind='line'
to draw the line graph.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
sns.set(style='darkgrid')
df = pd.DataFrame(dict(time=np.arange(500),
value=np.random.randn(500).cumsum()))
g = sns.relplot(x='time', y='value', kind='line', data=df)
g.fig.autofmt_xdate()
plt.show()
np.random.randn(500) will return a set of random sample values that obey the standard normal distribution. The cumsum() function will calculate the cumulative sum of the set of data and return an array of intermediate results. Simple example.
arr = np.random.randn(10)
print(arr)
print(arr.cumsum())
g.fig.autofmt_xdate() can rotate the angle of the data on the axis to prevent data overlap. You can use the parameter rotation to adjust the rotation angle as needed, the default is 30°.
We can also generate some time-type data to draw line graphs.
df = pd.DataFrame(dict(time=pd.date_range('2020-1-1', periods=500),
value=np.random.randn(500).cumsum()))
Show more relationships on one canvas.
If you use Matplotlib
one canvas to draw multiple graphs, you need to use subgraphs. The layout of the subgraphs is divided into rows and columns. Seaborn
The drawing layout is based on FacetGrid
objects. In the relplot
setting process col参数
, Seaborn
automatically subgraph layout on the same plane based on the data classification.
The fmri.csv
content of the file used here is as follows.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='darkgrid')
fmri = sns.load_dataset('fmri')
sns.relplot(x='timepoint', y='signal', hue='subject', col='region',
row='event', height=3, kind='line', estimator=None, data=fmri)
plt.show()
relplot
In the method, hue参数
adjust the color tone, col参数
adjust the column, row参数
adjust the row, height参数
adjust the size and line thickness of the graph.
When we want to check the effects of multiple levels of variables, it is best to divide the variables in columns and use wrap to wrap them into rows.
sns.relplot(x="timepoint", y="signal", hue="event", style="event",
col="subject", col_wrap=5,
height=3, aspect=.75, linewidth=2.5,
kind="line", data=fmri.query("region == 'frontal'"));