# librariesimport matplotlib.pyplot as plt
import numpy as np
# create dataset
height =[3,12,5,18,45]
bars =('A','B','C','D','E')
y_pos = np.arange(len(bars))# Create horizontal bars
plt.barh(y_pos, height)# Create names on the x-axis
plt.yticks(y_pos, bars)# Show graphic
plt.show()
2.条形图
# libraryimport matplotlib.pyplot as plt
# Create bars
barWidth =0.9
bars1 =[3,3,1]
bars2 =[4,2,3]
bars3 =[4,6,7,10,4,4]
bars4 = bars1 + bars2 + bars3
# The X position of bars
r1 =[1,5,9]
r2 =[2,6,10]
r3 =[3,4,7,8,11,12]
r4 = r1 + r2 + r3
# Create barplot
plt.bar(r1, bars1, width = barWidth, color =(0.3,0.1,0.4,0.6), label='Alone')
plt.bar(r2, bars2, width = barWidth, color =(0.3,0.5,0.4,0.6), label='With Himself')
plt.bar(r3, bars3, width = barWidth, color =(0.3,0.9,0.4,0.6), label='With other genotype')# Note: the barplot could be created easily. See the barplot section for other examples.# Create legend
plt.legend()# Text below each barplot with a rotation at 90°
plt.xticks([r + barWidth for r inrange(len(r4))],['DD','with himself','with DC','with Silur','DC','with himself','with DD','with Silur','Silur','with himself','with DD','with DC'], rotation=90)# Create labels
label =['n = 6','n = 25','n = 13','n = 36','n = 30','n = 11','n = 16','n = 37','n = 14','n = 4','n = 31','n = 34']# Text on the top of each barfor i inrange(len(r4)):
plt.text(x = r4[i]-0.5, y = bars4[i]+0.1, s = label[i], size =6)# Adjust the margins
plt.subplots_adjust(bottom=0.2, top =0.98)# Show graphic
plt.show()
3.堆叠条形图
# librariesimport matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
# Dataset:
a = pd.DataFrame({'group': np.repeat('A',500),'value': np.random.normal(10,5,500)})
b = pd.DataFrame({'group': np.repeat('B',500),'value': np.random.normal(13,1.2,500)})
c = pd.DataFrame({'group': np.repeat('B',500),'value': np.random.normal(18,1.2,500)})
d = pd.DataFrame({'group': np.repeat('C',20),'value': np.random.normal(25,4,20)})
e = pd.DataFrame({'group': np.repeat('D',100),'value': np.random.uniform(12, size=100)})
df=a.append(b).append(c).append(d).append(e)# plot violin chart
sns.violinplot( x='group', y='value', data=df)# add title
plt.title("Violin plot", loc="left")# show the graph
plt.show()
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\347106830.py:13: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
df=a.append(b).append(c).append(d).append(e)
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\347106830.py:13: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
df=a.append(b).append(c).append(d).append(e)
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\347106830.py:13: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
df=a.append(b).append(c).append(d).append(e)
4.-隐藏数据框图下
# librariesimport numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
# Data
r =[0,1,2,3,4]
raw_data ={'greenBars':[20,1.5,7,10,5],'orangeBars':[5,15,5,10,15],'blueBars':[2,15,18,5,10]}
df = pd.DataFrame(raw_data)# From raw value to percentage
totals =[i+j+k for i,j,k inzip(df['greenBars'], df['orangeBars'], df['blueBars'])]
greenBars =[i / j *100for i,j inzip(df['greenBars'], totals)]
orangeBars =[i / j *100for i,j inzip(df['orangeBars'], totals)]
blueBars =[i / j *100for i,j inzip(df['blueBars'], totals)]# plot
barWidth =0.85
names =('A','B','C','D','E')# Create green Bars
plt.bar(r, greenBars, color='#b5ffb9', edgecolor='white', width=barWidth)# Create orange Bars
plt.bar(r, orangeBars, bottom=greenBars, color='#f9bc86', edgecolor='white', width=barWidth)# Create blue Bars
plt.bar(r, blueBars, bottom=[i+j for i,j inzip(greenBars, orangeBars)], color='#a3acff', edgecolor='white', width=barWidth)# Custom x axis
plt.xticks(r, names)
plt.xlabel("group")# Show graphic
plt.show()
5.方块散点图
# librariesimport pandas as pd
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
# Create data frame with randomly selected x and y positions
df = pd.DataFrame(np.random.random((100,2)), columns=["x","y"])# Add a column: the color depends on x and y values, but you can use any function you want
value=(df['x']>0.2)&(df['y']>0.4)
df['color']= np.where( value==True,"#9b59b6","#3498db")# plot
sns.regplot(data=df, x="x", y="y", fit_reg=False, scatter_kws={'facecolors':df['color']})
plt.show()
# librariesimport matplotlib.pyplot as plt
import numpy as np
from scipy.stats import kde
# create data
x = np.random.normal(size=500)
y = x *3+ np.random.normal(size=500)# Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents
nbins=300
k = kde.gaussian_kde([x,y])
xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))# Make the plot
plt.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='auto')
plt.show()# Change color palette
plt.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='auto', cmap=plt.cm.Greens_r)
plt.show()
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\1895255686.py:12: DeprecationWarning: Please use `gaussian_kde` from the `scipy.stats` namespace, the `scipy.stats.kde` namespace is deprecated.
k = kde.gaussian_kde([x,y])
8. 避免重叠散点图中具有 2D 密度
# Librariesimport numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kde
# Create data: 200 points
data = np.random.multivariate_normal([0,0],[[1,0.5],[0.5,3]],200)
x, y = data.T
# Create a figure with 6 plot areas
fig, axes = plt.subplots(ncols=6, nrows=1, figsize=(21,5))# Everything starts with a Scatterplot
axes[0].set_title('Scatterplot')
axes[0].plot(x, y,'ko')# As you can see there is a lot of overlapping here!# Thus we can cut the plotting window in several hexbins
nbins =20
axes[1].set_title('Hexbin')
axes[1].hexbin(x, y, gridsize=nbins, cmap=plt.cm.BuGn_r)# 2D Histogram
axes[2].set_title('2D Histogram')
axes[2].hist2d(x, y, bins=nbins, cmap=plt.cm.BuGn_r)# Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents
k = kde.gaussian_kde(data.T)
xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))# plot a density
axes[3].set_title('Calculate Gaussian KDE')
axes[3].pcolormesh(xi, yi, zi.reshape(xi.shape), shading='auto', cmap=plt.cm.BuGn_r)# add shading
axes[4].set_title('2D Density with shading')
axes[4].pcolormesh(xi, yi, zi.reshape(xi.shape), shading='gouraud', cmap=plt.cm.BuGn_r)# contour
axes[5].set_title('Contour')
axes[5].pcolormesh(xi, yi, zi.reshape(xi.shape), shading='gouraud', cmap=plt.cm.BuGn_r)
axes[5].contour(xi, yi, zi.reshape(xi.shape))
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\129967845.py:28: DeprecationWarning: Please use `gaussian_kde` from the `scipy.stats` namespace, the `scipy.stats.kde` namespace is deprecated.
k = kde.gaussian_kde(data.T)
<matplotlib.contour.QuadContourSet at 0x15254b60790>
9.具有各种输入格式的 90 热图
# libraryimport seaborn as sns
import pandas as pd
import numpy as np
# Create a dataset
df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])# Default heatmap: just a visualization of this square matrix
sns.heatmap(df)
<Axes: >
10.自定义海生热图
# librariesimport seaborn as sns
import pandas as pd
import numpy as np
# Create a dataset
df = pd.DataFrame(np.random.random((10,10)), columns=["a","b","c","d","e","f","g","h","i","j"])# plot a heatmap with annotation
sns.heatmap(df, annot=True, annot_kws={"size":7})
<Axes: >
11.控制海生颜色热图
# librariesimport seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Create a dataset
df = pd.DataFrame(np.random.random((10,10)), columns=["a","b","c","d","e","f","g","h","i","j"])# plot using a color palette
sns.heatmap(df, cmap="YlGnBu")
plt.show()
sns.heatmap(df, cmap="Blues")
plt.show()
sns.heatmap(df, cmap="BuPu")
plt.show()
sns.heatmap(df, cmap="Greens")
plt.show()
12.制作调色板与海生
# Librariesimport seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# create data
x = np.random.rand(80)-0.5
y = x+np.random.rand(80)
z = x+np.random.rand(80)
df = pd.DataFrame({'x':x,'y':y,'z':z})# Plot with palette
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="Blues")
plt.show()# reverse palette
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="Blues_r")
plt.show()
13.海生主题
# librariesimport seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
# Data
data = np.random.normal(size=(20,6))+ np.arange(6)/2# Proposed themes: darkgrid, whitegrid, dark, white, and ticks
sns.set_style("whitegrid")
sns.boxplot(data=data)
plt.title("whitegrid")
plt.show()
sns.set_style("darkgrid")
sns.boxplot(data=data);
plt.title("darkgrid")
plt.show()
sns.set_style("white")
sns.boxplot(data=data);
plt.title("white")
plt.show()
sns.set_style("dark")
sns.boxplot(data=data);
plt.title("dark")
plt.show()
sns.set_style("ticks")
sns.boxplot(data=data);
plt.title("ticks")
plt.show()
14.seaborn-style-on-matplotlib-plot
# library and datasetfrom matplotlib import pyplot as plt
import pandas as pd
import numpy as np
# Create data
df=pd.DataFrame({'x_axis':range(1,101),'y_axis': np.random.randn(100)*15+range(1,101),'z':(np.random.randn(100)*15+range(1,101))*2})# plot with matplotlib
plt.plot('x_axis','y_axis', data=df, marker='o', color='mediumvioletred')
plt.show()
15.线图与 matplotlib
# librariesimport matplotlib.pyplot as plt
import numpy as np
# create data
values=np.cumsum(np.random.randn(1000,1))# use the plot function
plt.plot(values)# show the graph
plt.show()
16.折线图自定义
# Libraries and dataimport matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.DataFrame({'x_values':range(1,11),'y_values': np.random.randn(10)})# Draw plot
plt.plot('x_values','y_values', data=df, color='skyblue')
plt.show()# Draw line chart by modifiying transparency of the line
plt.plot('x_values','y_values', data=df, color='skyblue', alpha=0.3)# Show plot
plt.show()
17.多折线图
# librariesimport matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Data
df=pd.DataFrame({'x_values':range(1,11),'y1_values': np.random.randn(10),'y2_values': np.random.randn(10)+range(1,11),'y3_values': np.random.randn(10)+range(11,21)})# multiple line plots
plt.plot('x_values','y1_values', data=df, marker='o', markerfacecolor='blue', markersize=12, color='skyblue', linewidth=4)
plt.plot('x_values','y2_values', data=df, marker='', color='olive', linewidth=2)
plt.plot('x_values','y3_values', data=df, marker='', color='olive', linewidth=2, linestyle='dashed', label="toto")# show legend
plt.legend()# show graph
plt.show()
18.突出显示线中线图
# librariesimport matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Make a data frame
df=pd.DataFrame({'x':range(1,11),'y1': np.random.randn(10),'y2': np.random.randn(10)+range(1,11),'y3': np.random.randn(10)+range(11,21),'y4': np.random.randn(10)+range(6,16),'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6),'y6': np.random.randn(10)+range(2,12),'y7': np.random.randn(10)+range(5,15),'y8': np.random.randn(10)+range(4,14)})# Change the style of plot
plt.style.use('seaborn-darkgrid')# set figure size
my_dpi=96
plt.figure(figsize=(480/my_dpi,480/my_dpi), dpi=my_dpi)# plot multiple linesfor column in df.drop('x', axis=1):
plt.plot(df['x'], df[column], marker='', color='grey', linewidth=1, alpha=0.4)# Now re do the interesting curve, but biger with distinct color
plt.plot(df['x'], df['y5'], marker='', color='orange', linewidth=4, alpha=0.7)# Change x axis limit
plt.xlim(0,12)# Let's annotate the plot
num=0for i in df.values[9][1:]:
num+=1
name=list(df)[num]if name !='y5':
plt.text(10.2, i, name, horizontalalignment='left', size='small', color='grey')# And add a special annotation for the group we are interested in
plt.text(10.2, df.y5.tail(1),'Mr Orange', horizontalalignment='left', size='small', color='orange')# Add titles
plt.title("Evolution of Mr Orange vs other students", loc='left', fontsize=12, fontweight=0, color='orange')
plt.xlabel("Time")
plt.ylabel("Score")# Show the graph
plt.show()
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\876129807.py:10: MatplotlibDeprecationWarning: The seaborn styles shipped by Matplotlib are deprecated since 3.6, as they no longer correspond to the styles shipped by seaborn. However, they will remain available as 'seaborn-v0_8-<style>'. Alternatively, directly use the seaborn API instead.
plt.style.use('seaborn-darkgrid')
# librariesimport matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
# Dataset:
df=pd.DataFrame({'x': np.random.normal(10,1.2,20000),'y': np.random.normal(10,1.2,20000),'group': np.repeat('A',20000)})
tmp1=pd.DataFrame({'x': np.random.normal(14.5,1.2,20000),'y': np.random.normal(14.5,1.2,20000),'group': np.repeat('B',20000)})
tmp2=pd.DataFrame({'x': np.random.normal(9.5,1.5,20000),'y': np.random.normal(15.5,1.5,20000),'group': np.repeat('C',20000)})
df=df.append(tmp1).append(tmp2)# Plot with small marker size
plt.plot('x','y',"", data=df, linestyle='', marker='o', markersize=0.7)
plt.xlabel('Value of X')
plt.ylabel('Value of Y')
plt.title('Overplotting? Try to reduce the dot size', loc='left')
plt.show()
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\2806375468.py:11: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
df=df.append(tmp1).append(tmp2)
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\2806375468.py:14: UserWarning: linestyle is redundantly defined by the 'linestyle' keyword argument and the fmt string "" (-> linestyle='-'). The keyword argument will take precedence.
plt.plot( 'x', 'y', "", data=df, linestyle='', marker='o', markersize=0.7)
21.基本饼图
# libraryimport pandas as pd
import matplotlib.pyplot as plt
# --- dataset 2: 3 columns and rownames
df = pd.DataFrame({'var1':[8,3,4,2],'var2':[1,3,4,1]}, index=['a','b','c','d'])# make the multiple plot
df.plot(kind='pie', subplots=True, figsize=(16,8))# show the plot
plt.show()
22.基本甜甜圈图
# libraryimport matplotlib.pyplot as plt
# create data
size_of_groups=[12,11,3,30]# Create a pie plot
plt.pie(size_of_groups)#plt.show()# add a white circle at the center
my_circle=plt.Circle((0,0),0.7, color='white')
p=plt.gcf()
p.gca().add_artist(my_circle)# show the graph
plt.show()
23.改变甜甜圈图的背景
# libraryimport matplotlib.pyplot as plt
# Data
names ='groupA','groupB','groupC','groupD',
size =[12,11,3,30]# create a figure and set different background
fig = plt.figure()
fig.patch.set_facecolor('black')# Change color of text
plt.rcParams['text.color']='white'# Create a circle at the center of the plot
my_circle=plt.Circle((0,0),0.7, color='black')# Pieplot + circle on it
plt.pie(size, labels=names)
p=plt.gcf()
p.gca().add_artist(my_circle)
plt.show()
24.甜甜圈图与子组
# Librariesimport matplotlib.pyplot as plt
# Make data: I have 3 groups and 7 subgroups
group_names=['groupA','groupB','groupC']
group_size=[12,11,30]
subgroup_names=['A.1','A.2','A.3','B.1','B.2','C.1','C.2','C.3','C.4','C.5']
subgroup_size=[4,3,5,6,5,10,5,5,4,6]# Create colors
a, b, c=[plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]# First Ring (outside)
fig, ax = plt.subplots()
ax.axis('equal')
mypie, _ = ax.pie(group_size, radius=1.3, labels=group_names, colors=[a(0.6), b(0.6), c(0.6)])
plt.setp( mypie, width=0.3, edgecolor='white')# Second Ring (Inside)
mypie2, _ = ax.pie(subgroup_size, radius=1.3-0.3, labels=subgroup_names, labeldistance=0.7, colors=[a(0.5), a(0.4), a(0.3), b(0.5), b(0.4), c(0.6), c(0.5), c(0.4), c(0.3), c(0.2)])
plt.setp( mypie2, width=0.4, edgecolor='white')
plt.margins(0,0)# show it
plt.show()
25.基本棒棒糖剧情
# librariesimport matplotlib.pyplot as plt
import numpy as np
# create data
x=range(1,41)
values=np.random.uniform(size=40)# stem function
plt.stem(x, values)
plt.ylim(0,1.2)
plt.show()# stem function: If x is not provided, a sequence of numbers is created by python:
plt.stem(values)
plt.show()
26.自定义棒棒糖剧情
# librariesimport matplotlib.pyplot as plt
import numpy as np
# create data
values=np.random.uniform(size=40)# plot without markers
plt.stem(values, markerfmt=' ')
plt.show()# change color and shape and size and edges(markers, stemlines, baseline)= plt.stem(values)
plt.setp(markers, marker='D', markersize=10, markeredgecolor="orange", markeredgewidth=2)
plt.show()
27.垂直棒棒糖图
# librariesimport pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Create a dataframe
df = pd.DataFrame({'group':list(map(chr,range(65,85))),'values':np.random.uniform(size=20)})# Reorder it based on the values
ordered_df = df.sort_values(by='values')
my_range=range(1,len(df.index)+1)# The horizontal plot is made using the hline function
plt.hlines(y=my_range, xmin=0, xmax=ordered_df['values'], color='skyblue')
plt.plot(ordered_df['values'], my_range,"o")# Add titles and axis names
plt.yticks(my_range, ordered_df['group'])
plt.title("A vertical lolipop plot", loc='left')
plt.xlabel('Value of the variable')
plt.ylabel('Group')# Show the plot
plt.show()
28.棒棒糖-2组
# librariesimport numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Create a dataframe
value1=np.random.uniform(size=20)
value2=value1+np.random.uniform(size=20)/4
df = pd.DataFrame({'group':list(map(chr,range(65,85))),'value1':value1 ,'value2':value2 })# Reorder it following the values of the first value:
ordered_df = df.sort_values(by='value1')
my_range=range(1,len(df.index)+1)# The horizontal plot is made using the hline function
plt.hlines(y=my_range, xmin=ordered_df['value1'], xmax=ordered_df['value2'], color='grey', alpha=0.4)
plt.scatter(ordered_df['value1'], my_range, color='skyblue', alpha=1, label='value1')
plt.scatter(ordered_df['value2'], my_range, color='green', alpha=0.4, label='value2')
plt.legend()# Add title and axis names
plt.yticks(my_range, ordered_df['group'])
plt.title("Comparison of the value 1 and the value 2", loc='left')
plt.xlabel('Value of the variables')
plt.ylabel('Group')# Show the graph
plt.show()
29.棒棒糖-带条件颜色的情节
# librariesimport matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# Data
x = np.linspace(0,2*np.pi,100)
y = np.sin(x)+ np.random.uniform(size=len(x))-0.2# Create a color if the y axis value is equal or greater than 0
my_color = np.where(y>=0,'orange','skyblue')# The vertical plot is made using the vline function
plt.vlines(x=x, ymin=0, ymax=y, color=my_color, alpha=0.4)
plt.scatter(x, y, color=my_color, s=1, alpha=1)# Add title and axis names
plt.title("Evolution of the value of ...", loc='left')
plt.xlabel('Value of the variable')
plt.ylabel('Group')# Show the graph
plt.show()
30.基本面积图
# librariesimport numpy as np
import matplotlib.pyplot as plt
# Create data
x=range(1,6)
y=[1,4,6,8,4]# Area plot
plt.fill_between(x, y)# Show the graph
plt.show()# Note that we could also use the stackplot function# but fill_between is more convenient for future customization.#plt.stackplot(x,y)#plt.show()
31.改进面积图
# librariesimport numpy as np
import matplotlib.pyplot as plt
# create data
x=range(1,15)
y=[1,4,6,8,4,5,3,2,4,1,5,6,8,7]# Change the color and its transparency
plt.fill_between( x, y, color="skyblue", alpha=0.4)# Show the graph
plt.show()# Same, but add a stronger line on top (edge)
plt.fill_between( x, y, color="skyblue", alpha=0.2)
plt.plot(x, y, color="Slateblue", alpha=0.6)# See the line plot function to learn how to customize the plt.plot function# Show the graph
plt.show()
32.面积图和刻面
# librariesimport numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# Create a dataset
my_count=["France","Australia","Japan","USA","Germany","Congo","China","England","Spain","Greece","Marocco","South Africa","Indonesia","Peru","Chili","Brazil"]
df = pd.DataFrame({"country":np.repeat(my_count,10),"years":list(range(2000,2010))*16,"value":np.random.rand(160)})# Create a grid : initialize it
g = sns.FacetGrid(df, col='country', hue='country', col_wrap=4,)# Add the line over the area with the plot function
g = g.map(plt.plot,'years','value')# Fill the area with fill_between
g = g.map(plt.fill_between,'years','value', alpha=0.2).set_titles("{col_name} country")# Control the title of each facet
g = g.set_titles("{col_name}")# Add a title for the whole plot
plt.subplots_adjust(top=0.92)
g = g.fig.suptitle('Evolution of the value of stuff in 16 countries')# Show the graph
plt.show()
33.带白色网格的区域图
# librariesimport numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# set the seaborn style
sns.set_style("whitegrid")# Color palette
blue,= sns.color_palette("muted",1)# Create data
x = np.arange(23)
y = np.random.randint(8,20,23)# Make the plot
fig, ax = plt.subplots()
ax.plot(x, y, color=blue, lw=3)
ax.fill_between(x,0, y, alpha=.3)
ax.set(xlim=(0,len(x)-1), ylim=(0,None), xticks=x)# Show the graph
plt.show()
34.基本堆积面积图
# librariesimport numpy as np
import matplotlib.pyplot as plt
# --- FORMAT 1# Your x and y axis
x=range(1,6)
y=[[1,4,6,8,9],[2,2,7,10,12],[2,8,5,10,6]]# Basic stacked area chart.
plt.stackplot(x,y, labels=['A','B','C'])
plt.legend(loc='upper left')
plt.show()# --- FORMAT 2
x=range(1,6)
y1=[1,4,6,8,9]
y2=[2,2,7,10,12]
y3=[2,8,5,10,6]# Basic stacked area chart.
plt.stackplot(x,y1, y2, y3, labels=['A','B','C'])
plt.legend(loc='upper left')
plt.show()
35.堆积面积图的基线选项
# librariesimport numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Create data
X = np.arange(0,10,1)
Y = X +5* np.random.random((5, X.size))# There are 4 types of baseline we can use:
baseline =["zero","sym","wiggle","weighted_wiggle"]# Let's make 4 plots, 1 for each baselinefor n, v inenumerate(baseline):if n<3:
plt.tick_params(labelbottom='off')
plt.subplot(2,2, n +1)
plt.stackplot(X,*Y, baseline=v)
plt.title(v)
plt.tight_layout()
C:\Users\ASUS\AppData\Local\Temp\ipykernel_11108\3218836517.py:17: MatplotlibDeprecationWarning: Auto-removal of overlapping axes is deprecated since 3.6 and will be removed two minor releases later; explicitly call ax.remove() as needed.
plt.subplot(2 ,2, n + 1)
36.大熊猫堆积面积图
# librariesimport pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Dataset
df = pd.DataFrame(np.random.rand(10,4), columns=['a','b','c','d'])# plot
df.plot.area()# show the graph
plt.show()
37.堆积面积图
# librariesimport numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# Make data
data = pd.DataFrame({'group_A':[1,4,6,8,9],'group_B':[2,24,7,10,12],'group_C':[2,8,5,10,6],}, index=range(1,6))# We need to transform the data from raw data to percentage (fraction)
data_perc = data.divide(data.sum(axis=1), axis=0)# Make the plot
plt.stackplot(range(1,6), data_perc["group_A"], data_perc["group_B"], data_perc["group_C"], labels=['A','B','C'])
plt.legend(loc='upper left')
plt.margins(0,0)
plt.title('100 % stacked area chart')
plt.show()
38.散点图动画
# librariesimport matplotlib.pyplot as plt
import seaborn as sns
# grey background
sns.set(style="darkgrid")# Scatterplot with 1 data point
plt.scatter(1,10, s=600, alpha=0.5, edgecolors="grey", linewidth=2)
plt.xlim(0,10)
plt.ylim(0,100)
plt.show();
# Librariesimport matplotlib.pyplot as plt
import pandas as pd
from math import pi
# Set data
df = pd.DataFrame({'group':['A','B','C','D'],'var1':[38,1.5,30,4],'var2':[29,10,9,34],'var3':[8,39,23,24],'var4':[7,31,33,14],'var5':[28,15,32,14]})# number of variable
categories=list(df)[1:]
N =len(categories)# We are going to plot the first line of the data frame.# But we need to repeat the first value to close the circular graph:
values=df.loc[0].drop('group').values.flatten().tolist()
values += values[:1]
values
# What will be the angle of each axis in the plot? (we divide the plot / number of variable)
angles =[n /float(N)*2* pi for n inrange(N)]
angles += angles[:1]# Initialise the spider plot
ax = plt.subplot(111, polar=True)# Draw one axe per variable + add labels
plt.xticks(angles[:-1], categories, color='grey', size=8)# Draw ylabels
ax.set_rlabel_position(0)
plt.yticks([10,20,30],["10","20","30"], color="grey", size=7)
plt.ylim(0,40)# Plot data
ax.plot(angles, values, linewidth=1, linestyle='solid')# Fill area
ax.fill(angles, values,'b', alpha=0.1)# Show the graph
plt.show()