本文主要内容来自于天池课堂,本文在进行整理的同时在此注明原作者和原文链接,有兴趣的朋友可移步观看。
plt.plot(kind='line', ax=None, figsize=None, use_index=True, title=None, grid=None, legend=False, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, **kwds)
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) # pandas 时间序列ts = ts.cumsum()ts.plot(kind='line', label = "what", style = '--.', color = 'g', alpha = 0.4, use_index = True, rot = 45, grid = True, ylim = [-50,50], yticks = list(range(-50,50,10)), figsize = (8,4), title = 'TEST_TEST', legend = True)# 对网格项进行更加细致的设置#plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x') # 网格plt.legend()
# subplots → 是否将各个列绘制到不同图表,默认Falsedf = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')).cumsum()df.plot(kind='line', style = '--.', alpha = 0.4, use_index = True, rot = 45, grid = True, figsize = (8,4), title = 'test', legend = True, subplots = False, colormap = 'Greens')
面积图与线图非常相似。它们也被称为堆栈图。这些图可用于跟踪构成一个整体类别的两个或多个相关组的随时间变化。
fig,axes = plt.subplots(2,1,figsize = (8,6))df1 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])df2 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])df1.plot.area(colormap = 'Greens_r',alpha = 0.5,ax = axes[0])df2.plot.area(stacked=False,colormap = 'Set2',alpha = 0.5,ax = axes[1])for i in range(2): axes[i].legend(loc='upper left')
fig,axes = plt.subplots(2,1,figsize = (8,6))x = np.linspace(0, 1, 500)y1 = np.sin(4 * np.pi * x) * np.exp(-5 * x)y2 = -np.sin(4 * np.pi * x) * np.exp(-5 * x)axes[0].fill(x, y1, 'r',alpha=0.5,label='y1')axes[0].fill(x, y2, 'g',alpha=0.5,label='y2')# 对函数与坐标轴之间的区域进行填充,使用fill函数# 也可写成:plt.fill(x, y1, 'r',x, y2, 'g',alpha=0.5)x = np.linspace(0, 5 * np.pi, 1000) y1 = np.sin(x) y2 = np.sin(2 * x) axes[1].fill_between(x, y1, y2, color ='b',alpha=0.5,label='area') # 填充两个函数之间的区域,使用fill_between函数for i in range(2): axes[i].legend() axes[i].grid()# 添加图例、格网
条形图使用条形来比较不同类别之间的数据。当您想要测量一段时间内的变化时,它非常适合。它可以水平或垂直表示。此外,要记住的重要一点是,条形越长,价值就越大。
plt.plot(kind='bar/barh')
plt.bar/barh()
# 创建一个新的figure,并返回一个subplot对象的numpy数组fig,axes = plt.subplots(4,1,figsize = (10,10))s = pd.Series(np.random.randint(0,10,16),index = list('abcdefghijklmnop')) df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])# 单系列柱状图方法一:plt.plot(kind='bar/barh')s.plot(kind='bar',color = 'k',grid = True,alpha = 0.5,ax = axes[0]) # ax参数 → 选择第几个子图# 多系列柱状图df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])df.plot(kind='bar',ax = axes[1],grid = True,colormap='Reds_r')# 多系列堆叠图# stacked → 堆叠df.plot(kind='bar',ax = axes[2],grid = True,colormap='Blues_r',stacked=True)# The bars are positioned at y with the given align. Their dimensions are given by width and height. The horizontal baseline is left (default 0). # https://matplotlib.org/api/_as_gen/matplotlib.pyplot.barh.html?highlight=barh#matplotlib.pyplot.barhdf.plot.barh(ax = axes[3],grid = True,stacked=True,colormap = 'BuGn_r')
plt.figure(figsize=(10,4))x = np.arange(10)y1 = np.random.rand(10)y2 = -np.random.rand(10)plt.bar(x,y1,width = 1,facecolor = 'yellowgreen',edgecolor = 'white',yerr = y1*0.1)plt.bar(x,y2,width = 1,facecolor = 'lightskyblue',edgecolor = 'white',yerr = y2*0.1)for i,j in zip(x,y1): plt.text(i-0.2,j-0.15,'%.2f' % j, color = 'white')for i,j in zip(x,y2): plt.text(i-0.2,j+0.05,'%.2f' % -j, color = 'white')# 给图添加text# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
直方图用于显示分布,而条形图用于比较不同的实体。当您有阵列或很长的列表时,直方图很有用。让我们考虑一个例子,我需要使用箱子绘制不同年龄阶段的人口数。现在,箱子指的是被分成一系列间隔的值范围。箱子通常是相同尺寸的。plt.hist(x, bins=10, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical',rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)
# 直方图s = pd.Series(np.random.randn(1000))s.hist(bins = 20, histtype = 'bar', align = 'mid', orientation = 'vertical', alpha=0.5, density =True)# 密度图s.plot(kind='kde',style='k--')
# 堆叠直方图plt.figure(num=1)df = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000), 'c': np.random.randn(1000) - 1, 'd': np.random.randn(1000)-2}, columns=['a', 'b', 'c','d'])df.plot.hist(stacked=True, bins=20, colormap='Greens_r', alpha=0.5, grid=True)# 使用DataFrame.plot.hist()和Series.plot.hist()方法绘制df.hist(bins=50)# 生成多个直方图
array([[,],
[,]],
dtype=object)
通常我们需要散点图来比较变量,例如,一个变量受另一个变量的影响,以构建一个关系。数据显示为点的集合,每个点具有一个变量的值,该变量确定水平轴上的位置,而另一个变量的值确定垂直轴上的位置。plt.scatter(x, y, s=20, c=None, marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)
pd.plotting.scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, grid=False, diagonal='hist', marker='.', density_kwds=None, hist_kwds=None, range_padding=0.05, **kwds)
plt.figure(figsize=(8,6))x = np.random.randn(1000)y = np.random.randn(1000)plt.scatter(x,y,marker='.', s = np.random.randn(1000)*100, cmap = 'Reds_r', c = y, alpha = 0.8,)plt.grid()
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\collections.py:902: RuntimeWarning: invalid value encountered in sqrt
scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
# 散点矩阵df = pd.DataFrame(np.random.randn(100,4),columns = ['a','b','c','d'])pd.plotting.scatter_matrix(df,figsize=(10,6), marker = 'o', diagonal='kde', alpha = 0.5, range_padding=0.5)
array([[,,,],
[,,,],
[,,,],
[,,,]],
dtype=object)
饼图是指圆形图,它被分解成段,即饼图。它基本上用于显示百分比或比例数据,其中每个饼图片代表一个类别。
s = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')plt.axis('equal') # 保证长宽相等plt.pie(s, explode = [0.1,0,0,0], labels = s.index, colors=['r', 'g', 'b', 'c'], autopct='%.2f%%', pctdistance=0.6, labeldistance = 1.2, shadow = True, startangle=0, radius=1.0, frame=False)
([,,,],
[Text(1.24383,0.37802,'a'),
Text(0.546944,1.06811,'b'),
Text(-1.06749,0.548156,'c'),
Text(0.347639,-1.14854,'d')],
[Text(0.669752,0.203549,'9.39%'),
Text(0.273472,0.534053,'16.15%'),
Text(-0.533743,0.274078,'33.81%'),
Text(0.173819,-0.574271,'40.64%')])
箱型图又称为盒须图、盒式图、盒状图或箱线图,是一种用作显示一组数据分散情况资料的统计图。包含一组数据的:最大值、最小值、中位数、上四分位数(Q1)、下四分位数(Q3)、异常值。
plt.plot.box()
plt.boxplot()
箱型图着色
参数
# plt.plot.box()绘制fig,axes = plt.subplots(2,1,figsize=(10,6))df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')# 箱型图着色df.plot.box(ylim=[0,1.2], grid = True, color = color, ax = axes[0])df.plot.box(vert=False, positions=[1, 4, 5, 6, 8], ax = axes[1], grid = True, color = color)
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])plt.figure(figsize=(10,4))# 创建图表、数据f = df.boxplot(sym = 'o', # 异常点形状,参考marker vert = True, # 是否垂直 whis = 1.5, # IQR,默认1.5,也可以设置区间比如[5,95],代表强制上下边缘为数据95%和5%位置 patch_artist = True, # 上下四分位框内是否填充,True为填充 meanline = False,showmeans=True, # 是否有均值线及其形状 showbox = True, # 是否显示箱线 showcaps = True, # 是否显示边缘线 showfliers = True, # 是否显示异常值 notch = False, # 中间箱体是否缺口 return_type='dict' # 返回类型为字典 ) plt.title('boxplot')for box in f['boxes']: box.set( color='b', linewidth=1) # 箱体边框颜色 box.set( facecolor = 'b' ,alpha=0.5) # 箱体内部填充颜色for whisker in f['whiskers']: whisker.set(color='k', linewidth=0.5,linestyle='-')for cap in f['caps']: cap.set(color='gray', linewidth=2)for median in f['medians']: median.set(color='DarkBlue', linewidth=2)for flier in f['fliers']: flier.set(marker='o', color='y', alpha=0.5)# boxes, 箱线# medians, 中位值的横线,# whiskers, 从box到error bar之间的竖线.# fliers, 异常值# caps, error bar横线# means, 均值的横线,
# plt.boxplot()绘制# 分组汇总df = pd.DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )df['X'] = pd.Series(['A','A','A','A','A','B','B','B','B','B'])df['Y'] = pd.Series(['A','B','A','B','A','B','A','B','A','B'])df.boxplot(by = 'X')df.boxplot(column=['Col1','Col2'], by=['X','Y'])# columns:按照数据的列分子图# by:按照列分组做箱型图
array([,],
dtype=object)