Matplotlib可视化数据分析图表下(常用图表的绘制、折线图、柱形图、直方图、饼形图、散点图、面积图、热力图、箱形图、3D图表、绘制多个图表、双y轴可视化图表、颜色渐变图) | 您所在的位置:网站首页 › EXCEL绘制折线图两组数据 › Matplotlib可视化数据分析图表下(常用图表的绘制、折线图、柱形图、直方图、饼形图、散点图、面积图、热力图、箱形图、3D图表、绘制多个图表、双y轴可视化图表、颜色渐变图) |
本文来自《Python数据分析从入门到精通》_明日科技编著
5.6 常用图表的绘制
本节介绍常用图表的绘制,主要包括绘制折线图、绘制柱形图、绘制直方图、绘制饼形图、绘制散点图、绘制面积图、绘制热力图、绘制箱型图、绘制3D图表、绘制多个子图表以及图表的保存。对于常用的图表类型以绘制多种类型图表进行举例,以适应不同应用场景的需求。
5.6.1 绘制折线图
折线图可以显示一段时间内的连续数据,因此非常适合以等间隔显示数据的趋势。如基础体温图、学生成绩走势图、股票月度成交量走势图、月度销售额统计分析图、微博、公众号、网站访问统计图等,都可以用折线图来反映。在折线图中,类别数据沿水平轴均匀分布,所有值数据沿垂直轴均匀分布。
[En]
Line charts can display continuous data over time, so they are very suitable for showing trends in data at equal intervals. Such as basic body temperature graph, student performance trend chart, stock monthly trading volume trend chart, monthly sales statistical analysis chart, Weibo, official account, website visit statistical chart, and so on, can be reflected by line chart. In a line chart, category data is evenly distributed along the horizontal axis, and all value data is evenly distributed along the vertical axis.* Matplotlib绘制折线图主要使用plot()函数,相信通过前面的学习,您已经了解了plot()函数的基本用法,并能够绘制一些简单的折线图,下面尝试绘制多折线图。绘制学生语数外各科成绩分析图(12)使用plot()函数绘制多折线图。例如,绘制学生语数外各科成绩分析图,程序代码如下:import pandas as pdimport matplotlib.pyplot as pltdf1=pd.read_excel('data.xls') #导入Excel文件df1![]() ![]() for the above example, several parameters are used, which are explained below.* mfc:标记的颜色ms:标记的大小mec:标记边框的颜色alpha:透明度,设置该参数可以改变颜色的深浅5.6.2 绘制柱形图柱状图,又称条形图等,是以矩形长度为变量的统计图。条形图用于比较只有一个变量的两个或多个数据(在不同时间或不同条件下),通常用于较小的数据集分析。[En]column chart, also known as bar chart, etc., is a statistical chart with the length of a rectangle as a variable. Bar charts are used to compare two or more data (at different times or under different conditions) with only one variable and are usually used for smaller dataset analysis.* Matplotlib绘制柱形图主要使用bar()函数,语法如下:matplotlib.pyplot.bar(x,height,width,bottom=None,*,align='center',data=None,**kwargs)x:x轴数据height:柱子的高度,也就是y轴数据width:浮点型,柱子的宽度,默认值为0.8,可以指定固定值bottom:标量或数组,可选参数,柱形图的y坐标,默认值为None*:星号本身不是参数。星号表示其后面的参数为命名关键字参数,命名关键字参数必须传入参数名;否则程序会出现错误。align:对齐方式,如center(居中)和edge(边缘),默认值为centerdata:data关键字参数。如果给定一个数据参数,所有位置和关键字参数都将被替换**kwargs:关键字参数,其他可选参数,如color(颜色)、alpha(透明度)、label(每个柱子显示的标签)等。4行代码绘制简单的柱形图(13)import matplotlib.pyplot as pltx=[1,2,3,4,5,6]height=[10,20,30,40,50,60]plt.bar(x,height)![]() ![]() for the statistics of online book sales, if you want to count the sales of each platform, you can use multi-bar charts. Different colored columns represent different platforms, such as JD.com, Tmall, proprietary, etc. The program code is as follows:* import pandas as pdimport matplotlib.pyplot as pltdf = pd.read_excel('books.xlsx',sheet_name='Sheet2')plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码x=df['年份']y1=df['京东']y2=df['天猫']y3=df['自营']width =0.25 #柱子宽度,若显示n个柱子,则width值需小于1/n ,否则柱子会出现重叠#y轴标签plt.ylabel('线上销售额(元)')#图表标题plt.title('2013-2019年线上图书销售额分析图')plt.bar(x,y1,width = width,color = 'darkorange')plt.bar(x+width,y2,width = width,color = 'deepskyblue')plt.bar(x+2*width,y3,width = width,color = 'g')#设置每个柱子的文本标签,format(b,',')格式化销售额为千位分隔符格式# plt.text是设置文本的位置for a,b in zip(x,y1): plt.text(a, b,format(b,','), ha='center', va= 'bottom',fontsize=8)for a,b in zip(x,y2): plt.text(a+width, b,format(b,','), ha='center', va= 'bottom',fontsize=8)for a, b in zip(x, y3): plt.text(a + 2*width, b, format(b, ','), ha='center', va='bottom',fontsize=8)plt.legend(['京东','天猫','自营'])#图例![]() A histogram, also known as a mass distribution map, consists of a series of longitudinal stripes or line segments of different heights that represent the distribution of data. The horizontal axis is generally used to represent the data type, and the vertical axis is used to represent the distribution. A histogram is an accurate graphical representation of the distribution of numerical data and an estimation of the probability distribution of a continuous variable (quantitative variable).* 绘制直方图主要使用hist()函数,语法如下:matplotlib.pyplot.hist(x,bin=None,range=None,density=None,bottom=None,histtype='bar',align='mid',bog=False,color=None,labe=None,stacked=False,normed=None)x:数据集,最终的直方图将对数据集进行统计bins:统计数组的区间分布range:元组类型,显示的区间density:布尔型,显示的频率统计结果,默认值为None。设置值为False,不显示频率统计结果;设置值为True,则显示频率统计结果。需要统计结果=区间数目/(总数x区间宽度)。histtype:可选参数,设置值为bar、barstacked、step或stepfilled,默认值bar,推荐使用默认配置,其中step使用的是梯状,stepfilled则会对梯状内部进行填充,效果与bar类似。align:可选参数,控制柱状图的水平分布,设置值为left、mid或right,默认值为mid,其中,left或者right会有部分空白区域,推荐使用默认值。log:布尔型,默认值为False,即y坐标轴是否选择指数刻度。stacked:布尔型,默认值为False,是否为堆积柱状图。绘制简单直方图(16)import matplotlib.pyplot as pltx=[22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]plt.hist(x, bins = [0,25,50,75,100])![]() ![]() pie charts are often used to show the proportion of each part in the whole. For example, if you encounter the need to calculate the total cost or the amount of each part of the composition of the situation, generally through each part divided by the total to calculate, and this proportional representation method is very abstract, and through the pie chart will directly show the proportion of each component, clear at a glance.* Matplotlib绘制饼形图主要使用pie()函数,语法如下:matplotlib.pyplot.pie(x,explode=None,labels=None,colors=None,autopct=None,pctdistance=0.6,shadow=False,labeldistance=1.1,startangle=None,radius=None,counterclock=True,wedgeprops=None,textprops=None,center=(0,0),frame=False,rotatelabels=False,hold=None,data=None)x:每一块饼图的比例,如果sum(x) > 1会使用sum(x)归一化。explode:每一块饼图离中心的距离。labels:每一块饼图外侧显示的说明文字autopct:设置饼图百分比,可以使用格式化字符串format()函数。如’%1.1f’保留小数点前后1位。pctdistance:类似于labeldistance参数,指定百分比的位置刻度,默认值为0.6shadow:在饼图下面画一个阴影,默认值为False,即不画阴影。labeldistance:标记的绘制位置,相对于半径的比例,默认值为1.1,如设置值为90则从y轴正方向画起。radius:饼图半径,默认值为1counterclock:指定指针方向,布尔型,可选参数。默认值为True,表示逆时针;如果值为False,则表示顺时针wedgeprops:字典类型,可选参数,默认值为None。字典传递给wedge对象,用来画一个饼图。例如wedgeprops={‘linewidth’:2}设置wedge线宽为2. textprops:设置标签和比例文字的格式,字典类型,可选参数,默认值为None。传递给text对象的字典参数 center:浮点类型的列表,可选参数,默认值为(0,0),表示图表中心位置。 frame:布尔型,可选参数,默认值为False,不显示框架(也就是网络);如果值为True,则显示轴框架,与grid()函数配合使用。实际应用中建议使用默认设置,因为显示轴框架会干扰饼形图效果。 rotatelabels:布尔型,可选参数,默认值为False;如果值为True,则旋转每个标签到指定的角度。 绘制简单饼形图(18) import matplotlib.pyplot as plt x = [2,5,12,70,2,9] plt.pie(x,autopct='%1.1f%%')![]() analyze the proportion of sales by region through pie chart:* import pandas as pdfrom matplotlib import pyplot as pltdf1 = pd.read_excel('data2.xls')plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码plt.figure(figsize=(5,3)) #设置画布大小labels = df1['地区']sizes = df1['销量']#设置饼形图每块的颜色colors = ['red', 'yellow', 'slateblue', 'green','magenta','cyan','darkorange','lawngreen','pink','gold']plt.pie(sizes, #绘图数据 labels=labels,#添加区域水平标签 colors=colors,# 设置饼图的自定义填充色 labeldistance=1.02,#设置各扇形标签(图例)与圆心的距离 autopct='%.1f%%',# 设置百分比的格式,这里保留一位小数 startangle=90,# 设置饼图的初始角度 radius = 0.5, # 设置饼图的半径 center = (0.2,0.2), # 设置饼图的原点 textprops = {'fontsize':9, 'color':'k'}, # 设置文本标签的属性值 pctdistance=0.6)# 设置百分比标签与圆心的距离# 设置x,y轴刻度一致,保证饼图为圆形plt.axis('equal')plt.title('2020年1月各地区销量占比情况分析')![]() split pie chart is to split what you think is the main part of the pie chart for the purpose of highlighting.* 拆分销售占比最大的广东省,效果如下图所示拆分饼图可以同时拆分多个部分,如下图所示。[En]split Guangdong Province, which accounts for the largest proportion of sales, and the effect is shown in the first picture below. A split pie chart can split multiple pieces at the same time, as shown in the second figure below.* import pandas as pdfrom matplotlib import pyplot as pltdf1 = pd.read_excel('data2.xls')plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码plt.figure(figsize=(5,3)) #设置画布大小labels = df1['地区']sizes = df1['销量']#设置饼形图每块的颜色colors = ['red', 'yellow', 'slateblue', 'green','magenta','cyan','darkorange','lawngreen','pink','gold']plt.pie(sizes, #绘图数据 labels=labels,#添加区域水平标签 colors=colors,# 设置饼图的自定义填充色 labeldistance=1.02,#设置各扇形标签(图例)与圆心的距离 autopct='%.1f%%',# 设置百分比的格式,这里保留一位小数 startangle=90,# 设置饼图的初始角度 radius = 0.5, # 设置饼图的半径 center = (0.2,0.2), # 设置饼图的原点 textprops = {'fontsize':9, 'color':'k'}, # 设置文本标签的属性值 pctdistance=0.6,# 设置百分比标签与圆心的距离 #shadow=True, #阴影 explode = (0.1,0,0,0,0,0,0,0,0,0)) #设置分裂饼图 #explode = (0.1,0,0,0,0,0,0,0.1,0.1,0)) #设置多分裂饼图# 设置x,y轴刻度一致,保证饼图为圆形plt.axis('equal')plt.title('2020年1月各地区销量占比情况分析')![]() ![]() the pie chart with shadow looks more beautiful, as shown in the following figure:* 立体感带阴影的饼形图主要通过shadow参数实现,设置该参数值为True即可,主要代码如下:shadow=True, #阴影import pandas as pdfrom matplotlib import pyplot as pltdf1 = pd.read_excel('data2.xls')plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码plt.figure(figsize=(5,3)) #设置画布大小labels = df1['地区']sizes = df1['销量']#设置饼形图每块的颜色colors = ['red', 'yellow', 'slateblue', 'green','magenta','cyan','darkorange','lawngreen','pink','gold']plt.pie(sizes, #绘图数据 labels=labels,#添加区域水平标签 colors=colors,# 设置饼图的自定义填充色 labeldistance=1.02,#设置各扇形标签(图例)与圆心的距离 autopct='%.1f%%',# 设置百分比的格式,这里保留一位小数 startangle=90,# 设置饼图的初始角度 radius = 0.5, # 设置饼图的半径 center = (0.2,0.2), # 设置饼图的原点 textprops = {'fontsize':9, 'color':'k'}, # 设置文本标签的属性值 pctdistance=0.6,# 设置百分比标签与圆心的距离 shadow=True, #阴影 explode = (0.1,0,0,0,0,0,0,0,0,0)) #设置分裂饼图,本例中第一个数字最大 #explode = (0.1,0,0,0,0,0,0,0.1,0.1,0)) #设置多分裂饼图# 设置x,y轴刻度一致,保证饼图为圆形plt.axis('equal')plt.title('2020年1月各地区销量占比情况分析')![]() A ring chart is a figure formed by digging out the middle part of two or more pie charts of different sizes. The results are as follows:.* import pandas as pdfrom matplotlib import pyplot as pltdf1 = pd.read_excel('data2.xls')plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码plt.figure(figsize=(5,3)) #设置画布大小labels = df1['地区']sizes = df1['销量']#设置饼形图每块的颜色colors = ['red', 'yellow', 'slateblue', 'green','magenta','cyan','darkorange','lawngreen','pink','gold']plt.pie(sizes, #绘图数据 labels=labels,#添加区域水平标签 colors=colors,# 设置饼图的自定义填充色 autopct='%.1f%%',# 设置百分比的格式,这里保留一位小数 #radius =1 , # 设置饼图的半径 pctdistance=0.85, startangle = 180, textprops = {'fontsize':9, 'color':'k'}, # 设置文本标签的属性值 wedgeprops = {'width': 0.4, 'edgecolor': 'k'})plt.title('2020年1月各地区销量占比情况分析')![]() the embedded ring graph is actually a double ring graph, and the effect is as follows:* import pandas as pdimport matplotlib.pyplot as pltplt.rcParams['font.sans-serif']=['SimHei']df1 = pd.read_excel('data2.xls')df2=pd.read_excel('data2.xls',sheet_name='2月')#数据集,x1,x2分别对应外环、内环百分比例x1=df1['销量']x2=df2['销量']#设置饼状图各个区块的颜色colors = ['red', 'yellow', 'slateblue', 'green','magenta','cyan','darkorange','lawngreen','pink','gold']#外环plt.pie(x1,autopct='%.1f%%',radius=1,pctdistance=0.85,colors=colors,wedgeprops=dict(linewidth=2,width=0.3,edgecolor='w'))#内环plt.pie(x2,autopct='%.1f%%',radius=0.7,pctdistance=0.7,colors=colors,wedgeprops=dict(linewidth=2,width=0.4,edgecolor='w'))#图例legend_text=df1['地区']plt.legend(legend_text,title='地区',frameon=False,bbox_to_anchor=(0.2,0.5))#设置图例标题、位置、去掉图例边框plt.axis('equal')#设置坐标轴比例以显示为圆形plt.title('2020年1月和2月各地区销量占比情况分析')![]() the following three points should be paid attention to in drawing a nested ring diagram:* (1)连续使用两次pie()函数。(2)通过wedgeprops参数设置环形边界。(3)通过radius参数设置不同的半径。另外,由于图例内容比较长,为了图例能够正常显示,图例代码中引入了两个主要参数,即frameon和bboox_to_anchor。其中,frameon参数设置图例有无边框;bbox_to_anchor参数设置图例位置,主要代码如下:#外环plt.pie(x1,autopct='%.1f%%',radius=1,pctdistance=0.85,colors=colors,wedgeprops=dict(linewidth=2,width=0.3,edgecolor='w'))#内环plt.pie(x2,autopct='%.1f%%',radius=0.7,pctdistance=0.7,colors=colors,wedgeprops=dict(linewidth=2,width=0.4,edgecolor='w'))#图例legend_text=df1['地区']plt.legend(legend_text,title='地区',frameon=False,bbox_to_anchor=(0.2,0.5))#设置图例标题、位置、去掉图例边框5.6.5 绘制散点图散点图主要用于查看数据的分布或相关性,通常在线性回归分析中,以查看数据点在坐标系平面的分布。散点图显示了因变量随自变量变化的一般趋势,据此可以选择合适的函数来拟合数据。[En]scatter plots are mainly used to view the distribution or correlation of data, generally in linear regression analysis, to view the distribution of data points in the coordinate system plane. The scatter plot shows the general trend of the dependent variable changing with the independent variable, based on which the appropriate function can be selected to fit the data.* 像折线图一样,散点图是由单个点组成的。但不同的是,散点图中的点并不是按照它们之间的关系用直线连接的。[En]like a line chart, a scatter chart is made up of individual points. But the difference is that the points of the scatter graph are not connected by lines according to the relationship between them.* Matplotlib绘制散点图使用plot()函数和scatter()函数都可以实现,本节使用scatter()函数绘制散点图,scatter()函数专门用于绘制散点图,使用方式和plot()函数类似,区别在于前者具有更高的灵活性,可以单独控制每个散点与数据匹配,并让每个散点具有不同的属性。scatter()函数的语法如下:matplotlib.pyplot.scatter(x,y,s=None,marker=None,cmap=None,norm=None,vmax=None,alpha=None,linewidths=None,verts=None,edgecolors=None,data=None,**kwargs)x,y:数据s:标记大小,以平方磅为单位的标记面积,设置值如下。数值标量:以相同的大小绘制所有标记。行或列向量:是每个标记具有不同的大小。x、y和sz中的相应元素确定每个标记的位置和面积。sz的长度必须等于x和y的长度。[]:使用36平方磅的默认面积。c:标记颜色,可选参数,默认标记颜色为蓝色marker:标记样式,可选参数,默认值为’o’cmap:颜色地图,可选参数,默认值为Nonenorm:可选参数,默认值为Nonevmin,vmax:标量,可选,默认值为Nonealpha:透明度,可选参数,0~1的数,表示透明度,默认值为Nonelinewidths:线宽,标记边缘的宽度,可选参数,默认值为Noneverts:(x,y)的序列,可选参数,如果参数marker为None,这些顶点将用于构建标记。标记的中心位置为(0,0)edgecolors:轮廓颜色,与参数c类似,可选参数,默认值为Nonedata:data关键字参数。如果给定一个数据参数,所有位置和关键字参数将被替换**kwargs:关键字参数,其他可选参数绘制简单散点图(23)import matplotlib.pyplot as pltx=[1,2,3,4,5,6]y=[19,24,37,43,55,68]plt.scatter(x, y)![]() next, draw a scatter chart of sales revenue and advertising fees to observe the correlation between sales revenue and advertising fees:* import pandas as pdimport matplotlib.pyplot as pltaa =r'JDdata.xls'bb=r'JDcar.xls'dfaa = pd.DataFrame(pd.read_excel(aa))dfbb=pd.DataFrame(pd.read_excel(bb))df1=dfaa[['业务日期','金额']]df2=dfbb[['投放日期','支出']]df1![]() ![]() ![]() ![]() ![]() area maps are used to reflect the extent to which the quantity changes over time, and can also be used to draw attention to the trend of the total value. For example, data that represents profits that change over time can be plotted in an area chart to emphasize total profits.* Matplotlib绘制面积图主要使用stackplot()函数,语法如下:matplotlib.pyplot.stackplot(x,*args,data=None,**kwargs)x:x轴数据_args:当传入的参数个数未知时使用_args。这里指y轴数据可以传入多个y轴。data:data关键字参数。如果给定一个数据参数,所有位置和关键字参数将被替换。**kwargs:关键字参数,其他可选参数,如color(颜色)、alpha(透明度)等。绘制简单面积图(25)import matplotlib.pyplot as pltx = [1,2,3,4,5]y1 =[6,9,5,8,4]y2 = [3,2,5,4,3]y3 =[8,7,8,4,3]y4 = [7,4,6,7,12]plt.stackplot(x, y1,y2,y3,y4, colors=['g','c','r','b'])![]() there are also many kinds of area maps, such as standard area map, stacked area map and percentage stacked area map. The standard stacking area diagram is mainly introduced below.* 1.标准面积图(26)通过标准面积图分析2013-2019年线上图书销售情况,通过该图可以看出每一年线上图书销售的一个趋势:import pandas as pdimport matplotlib.pyplot as pltdf = pd.read_excel('books.xlsx')plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码x=df['年份']y=df['销售额']#图表标题plt.title('2013-2019年线上图书销售情况')plt.stackplot(x, y)![]() ![]() A thermal map is a heat map that is visualized by a density function to represent the density in a map. It enables people to perceive the density of points independently of the scaling factor. The thermal map can show what is happening in the unclickable area. Using the thermal map, we can see the similarity of multiple features in the data table. For example, an illustration of the area of the page and the geographic area where the visitor is located is displayed in a specially highlighted form. Thermal map is also widely used in web page analysis, business data analysis and other fields.* 绘制简单热力图(28)热图是常用的数据分析方法,通过色差和亮度显示数据的差异,通俗易懂。[En]Thermal map is a common method of data analysis, which shows the difference of data through color difference and brightness, which is easy to understand.* import matplotlib.pyplot as pltX = [[1,2],[3,4],[5,6],[7,8],[9,10]]plt.imshow(X)![]() draw the thermal map according to the statistical data of students’ scores, and directly compare the scores of each student in each subject through the thermal map. The program code is as follows:* import pandas as pdimport matplotlib.pyplot as pltdf = pd.read_excel('data1.xls',sheet_name='高二一班')plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码X = df.loc[:,"语文":"生物"].valuesname=df['姓名']plt.imshow(X)plt.xticks(range(0,6,1),['语文','数学','英语','物理','化学','生物'])#设置x轴刻度标签plt.yticks(range(0,12,1),name)#设置y轴刻度标签plt.colorbar() #显示颜色条plt.title('学生成绩统计热力图')![]() as can be seen from the picture above, the higher the score is when the color is highlighted; on the contrary, the lower the score is.* 5.6.9 绘制箱形图箱型图又称箱线图、盒须图或盒式图,它是一种显示一组数据分散情况下的资料的统计图。因形状像箱子而得名。 箱形图最大的优点就是不受异常值的影响,可以以一种相对稳定的方式描述数据的离散程度分布情况,因此在各种领域经常被使用。另外,箱形图也常用于异常值的识别。Matplotlib绘制箱型图主要使用boxplot()函数,语法如下:matplotlib.pyplot.boxplot(x,notch=None,sym=None,vert=None,whis=None,positon=None,widths=None,patch_artist=None,meanline=None,showmeans=None,showcaps=None,showbox=None,showfiers=None,boxprops=None,labels=None,flierprops=None,medianprops=None,meanprops=None,capprops=None,whiskerprops=None)x:指定要绘制箱型图的数据notch:是否以凹口的形式展现箱形图,默认非凹口sym:指定异常点的形状,默认为加号(+)显示vert:是否需要将箱形图垂直摆放,默认垂直摆放whis:指定上下限于与上下四分位的距离,默认为1.5倍的四分位差。position:指定箱形图的位置,默认为[0,1,2,…]widths:指定箱形图的宽度,默认为0.5patch_artist:是否填充箱体的颜色。meanline:是否用线的形式表示均值,默认用点来显示。showmeans:是否显示均值,默认不显示showcaps:是否显示箱形图顶端和末端的两条线,默认显示。showbox:是否显示箱形图的箱体,默认显示。showfliers:是否显示异常值,默认显示。boxprops:设置箱体的属性,如异常点的形状、大小、填充色等。medianprops:设置中位数的属性,如线的类型、粗细等。meanprops:设置均值的属性,如点的大小、颜色等。capprops:设置箱形图顶端和末端线条的属性,如颜色、粗细等。whiskerprops:设置须的属性,如颜色、粗细等。绘制简单箱形图(30)import matplotlib.pyplot as pltx=[1,2,3,5,7,9]plt.boxplot(x)![]() the above example is a box diagram of a group of data. You can also draw a box diagram of multiple groups of data, and you need to specify multiple groups of data. For example, to draw a box diagram for three sets of data, the program code is as follows:* import matplotlib.pyplot as pltx1=[1,2,3,5,7,9]x2=[10,22,13,15,8,19]x3=[18,31,18,19,14,29]plt.boxplot([x1,x2,x3])![]() the box diagram separates the data (in effect, dividing the data into four parts), as shown in figure 5.57.* ![]() the following describes the specific meaning of each part of the box diagram and how to identify outliers through the box diagram.* 下四分位:图5.57中的下四分位数指的是数据的25%分位点所对应的值(Q1)。计算分位数可以使用Pandas的quantile()函数。例如,Q1=df[‘总消费’].quantile(q=0.25)。中位数:中位数即为数据的50%分位点所对应的值(Q2)上四分位数:上四分位数则为数据的75%分位点所对应的值(Q3)上限:上线的计算公式为Q3+1.5(Q3-Q1)下限:上线的计算公式为Q1-1.5(Q3-Q1)其中Q3-Q1表示四分位差。如果使用箱形图识别异常值,其判断标准是,当变量的数据值大于箱形图的上限或者小于箱形图的下限时,就可以将这样的数据判定为异常值。学习以下判断异常值的算法,如图5.58所示。[En]learn the following algorithm for judging outliers, as shown in figure 5.58.* ![]() find the outliers in the total guest consumption data through the box chart. The program code is as follows:* import matplotlib.pyplot as pltimport pandas as pddf=pd.read_excel('tips.xlsx')plt.boxplot(x = df['总消费'], # 指定绘制箱线图的数据 whis = 1.5, # 指定1.5倍的四分位差 widths = 0.3, #指定箱线图中箱子的宽度为0.3 patch_artist = True, #填充箱子颜色 showmeans = True, #显示均值 boxprops = {'facecolor':'RoyalBlue'}, # 指定箱子的填充色为宝蓝色 flierprops = {'markerfacecolor':'red', 'markeredgecolor':'red', 'markersize':3}, # 指定异常值的填充色、边框色和大小 meanprops = {'marker':'h','markerfacecolor':'black', 'markersize':8},# 指定均值点的标记符号(六边形)、填充色和大小 medianprops = {'linestyle':'--','color':'orange'}, # 指定中位数的标记符号(虚线)和颜色 labels = ['']) # 去除x轴刻度值# 计算下四分位数和上四分位Q1 = df['总消费'].quantile(q = 0.25)Q3 = df['总消费'].quantile(q = 0.75)# 基于1.5倍的四分位差计算上下限对应的值low_limit = Q1 - 1.5*(Q3 - Q1)up_limit = Q3 + 1.5*(Q3 - Q1)# 查找异常值val=df['总消费'][(df['总消费'] > up_limit) | (df['总消费'] < low_limit)]print('异常值如下:')print(val)![]() ![]() ![]() ![]() ![]() ![]() 图5.65 对于上述例子,必须掌握以下两个关键点。 [En]for the above examples, the following two key points must be mastered.* (1)每绘制一个子图表都要调用一次subplot()函数(2)绘图区域位置编号subplot()函数的前面两个参数指定的是一个画布被分割成的行数和列数,后面一个参数则指的是当前绘制区域位置编号,编号规则是行优先。例如,图5.64中有3个子图表,第1个子图表subplot(2,2,1),即将画布分成2行2列,在第1个子图中绘制折线图;第二子图表subplot(2,2,2),将画布分成2行2列,在第二个子图中绘制散点图;第3个子图表subplot(2,1,2),将画布分成2行1列,由于第1行已经占用了,所以在第2行也就是第3个子图中绘制柱形图。示意图如图5.65所示。![]() ![]() ![]() for example, save the previously drawn line chart, the main code is as follows:* plt.savefig('image.png')需要注意一个关键问题,保存代码必须在图表预览前,也就是plt.show()代码前;否则保存后的图片是白色,图表无法保存。5.7 综合应用5.7.1 双y轴可视化数据分析图表的实现双y轴顾名思义就是两个y轴,其特点是通过双y轴看出发展情况的同时还可以看到其增长速度。对于产品而言,通过此图可以看到产品销量的同时还可以看到产品增长率,效果如下:import pandas as pdimport matplotlib.pyplot as pltdf=pd.read_excel('mrbook.xlsx') #导入Excel文件x=[1,2,3,4,5,6]y1=df['销量']y2=df['rate']fig = plt.figure()plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号ax1 = fig.add_subplot(111) #添加子图plt.title('销量情况对比') #图表标题#图表x轴标题plt.xticks(x,['1月','2月','3月','4月','5月','6月'])ax1.bar(x,y1,label='销量')lin1=ax1.legend(('销量',)) #设置图例ax1.set_ylabel('销量(册)') #y轴标签ax2 = ax1.twinx() #共享x轴添加一条y轴坐标轴ax2.plot(x,y2,color='black',linestyle='--',marker='o',linewidth=2,label='增长率')ax2.set_ylabel('增长率')lin2=ax2.legend(('增长率',))for a,b in zip(x,y2): plt.text(a, b+0.02, '%.2f' % b, ha='center', va= 'bottom',fontsize=10,color='red')plt.show()![]() ![]() if you draw a split pie chart, you can search for the key word “split pie chart” in this article.* 颜色渐变主要使用了Matplotlib内置颜色地图模块cm,在该模块中指定一组数据可以生成多种颜色,由浅入深。例如,渐变蓝色,cmap=plt.cm.Blues。5.7.3 等高线图的实现等值线地图是在地理课上讨论峰谷时绘制的,也将用于机器学习绘制梯度下降算法的图形。等高线图的实现结果如下图所示:[En]Contour maps are drawn when talking about peaks and valleys in geography class, and will also be used in machine learning to draw the graph of gradient descent algorithm. The implementation result of the contour map is shown in the following figure:* import numpy as npimport matplotlib.pyplot as plt# 计算x,y坐标对应的高度值def f(x, y): return (1-x/2+x**5+y**3) * np.exp(-x**2-y**2)# 生成x,y的数据n = 256x = np.linspace(-3, 3, n)y = np.linspace(-3, 3, n)# 把x,y数据转换为二维数据X, Y = np.meshgrid(x, y)# 填充等高线plt.contourf(X, Y, f(X, Y))# 显示图表plt.show()![]() Original: https://blog.csdn.net/Triumph19/article/details/125667265Author: Triumph19Title: Matplotlib可视化数据分析图表下(常用图表的绘制、折线图、柱形图、直方图、饼形图、散点图、面积图、热力图、箱形图、3D图表、绘制多个图表、双y轴可视化图表、颜色渐变图) 相关阅读 Title: 【Grafana】Grafana Mimir在海量时间序列指标中的优化 Grafana Mimir在海量时间序列指标中的优化 前言 正文 * 指标采集的挑战 – 大量数据的产生 块压缩缓慢 TSDB的限制 Mimir的优化 – 特性一:对输入的块进行分组 特性二:对数据进行分片 特性三:如何合并分片 Mimir如何进行压缩 前言事实上我也是最近看Grafana的博客时才了解到Mimir的。 Grafana Mimir 是 Grafana Labs 新开源的项目,用来为 Prometheus 提供持久化存储,开源许可协议是 AGPL-3.0。此前 Grafana 开源了 Cortex,但 Grafana Cloud 使用的还是内部商用的存储,因此 Grafana 团队需要维护两套代码。也许是维护两套代码太累了,所以干脆将 Grafana Cloud 使用的存储开源了,就是 Grafana Mimir。 ![]() Grafan给出了一些使用Mimir的原因: ![]() 未来Grafana还计划对更多的数据源进行兼容。 简单了解了Mimir,本文主要是阅读了开发团队发布的最新博文后写的,感兴趣的可以直接看原文,可能有些地方理解不够的或者理解有误的,还请指正: 原文地址: How Grafana Mimir’s split-and-merge compactor enables scaling metrics to 1 billion active series ; 正文 指标采集的挑战 大量数据的产生根据原文所说,Cortex在进行指标拉取的时候所面临的一个挑战就是越多的指标需要越多的摄取组件实例,同时考虑到3副本的情况下,若每个摄取器能够处理1kw的时间序列,10亿的时间序列就需要300个实例; OK,随着摄取器实例的增多,面临的新问题是这么多的实例,每2小时生成一个TSDB块,一天会新增3600个TSDB块,一天大约会产生20TB的数据;如此大体量的数据,使用Grafana进行可视化的时候会明显感觉到延迟,Mimir通过压缩解决了数据膨胀以及重复数据的问题; 块压缩缓慢对于Cortex和Prometheus存在两个问题,第一个是数据块存储压缩流程,在Cortex中,压缩是单线程任务,因此这个过程会很慢,而且未压缩的块给查询器和存储网关增加了压力,而且它们的查询速度很慢; ![]() 另一个问题是,Prometheusde TSDB规则是总索引大小限制为64gib,每个索引段限制为4gib,上述压缩出来的块会打破这个限制。 Mimir的优化 特性一:对输入的块进行分组针对上述的大量数据的问题,Mimir对输入的数据块进行了分组然后并行处理的方式,而不是一次性压缩所有摄入数据;例如,运行15个小的压缩,而不是一个包含300个块的大压缩,每个合并20个块,这虽然解决了大量输入数据的问题,但是大量数据中的重复数据删除并没有得到很好的处理; ![]() 在压缩过程中,Mimir会对指标序列进行分片,以达到将不同块中的相同序列压缩在一起的目的;这个过程中,输入数据会根据其hash值以及配置的输出块数量来进行分片,比如,原本压缩为一个输出块的情况,现在会压缩成3个,这将会避免超出Prometheus的TSDB限制: ![]() the configurable number of fragments allows for a very large active sequence that previously could not be put into a single block.* 能够准确的知道每个block中存在哪些时间序列;合并多个具有相同分片ID的块将会维持他们的分片ID,比如”5_of_32″ ;特性三:如何合并分片上一部分提到过 并多个具有相同分片ID的块将会维持他们的分片ID 假设现在有一个块包含的时间跨度为6-8点, today from 6:00 to 8:00, with shard ID 5_of_32,另一个块包含的时间跨度为8-10点, today between 8:00 and 10:00, shard ID 5_of_32,可以将这两个块合并为一个更大的快,即 today from 6:00 to 10:00, shard ID 5_of_32; 合并之后,对于这个块中包含的每个系列,属性series.hash() mod 32 == 5仍然有效,该功能允许将传统的块合并为多个分片的12小时或24小时块,这是一个可重复的操作,对相同的数据再做一次会产生相同的结果,也就是说 多个摄取器拿到的数据做过合并后的块依旧是相同的副本 该设计保证了多副本的重复数据的清理能够有效进行,因为相同的数据一定存在于相同的分片中 此操作依赖于模操作,上文的mod为32,mod32的分片只能和mod32的合并,如果更改为mod48了,那就不能进行合并了,因为无法再保证数据存在于相同分片 Mimir如何进行压缩说完了Mimir的一些优化特性,就开始看Mimir如何进行压缩工作了;对于Mimir来说,每个compactor(压缩器)会运行一个planner(计划器),计划器会聚焦于存储载体上的所有可用块,找到需要被压缩的块,然后计算压缩工作。 压缩器会执行两种工作: Split Job:拆分工作,摄取器产生的块会先备份组,每个组的块稍后会被分别单独压缩(特性一),在这个压缩过程中,同时会对输出的块做分片(特性二); Merge Job:合并工作会对相同分片的块做合并(特性三),如果一个块没有被拆分split,它将拥有一个可用于匹配和合并的空的分片ID;每个压缩器实例运行的计划器会计算所有拆分和合并作业,这取决于计划器运行时存储块的当前状态。然而,一个压缩器实例只会运行器”拥有的”工作,这将取决于Mimir的hash环,具体可查看官网原文:Grafana Mimir hash rings Grafana Mimir的拆分合并压缩器可以轻松地在许多压缩器实例中分配拆分和合并工作,加快整体压缩过程,简而言之: 更多的压缩器,更快的速度! Original: https://www.cnblogs.com/Meepoljd/p/16625236.htmlAuthor: 风灵动铭Title: 【Grafana】Grafana Mimir在海量时间序列指标中的优化 原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/325281/ 转载文章受原作者版权保护。转载请注明原作者出处! |
CopyRight 2018-2019 实验室设备网 版权所有 |