Seaborn visualized drawing line graph

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 Seabornthe relplotmethod 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()

Insert picture description here

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())

Insert picture description here
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()))

Insert picture description here

Show more relationships on one canvas.
If you use Matplotlibone canvas to draw multiple graphs, you need to use subgraphs. The layout of the subgraphs is divided into rows and columns. SeabornThe drawing layout is based on FacetGridobjects. In the relplotsetting process col参数, Seabornautomatically subgraph layout on the same plane based on the data classification.
The fmri.csvcontent of the file used here is as follows.
Insert picture description here

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()

relplotIn 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.
Insert picture description here
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'"));

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43965708/article/details/112984843