Use Python to draw commonly used charts

Source: Internet
Author: User
Tags border color
This article introduces you how to use Python to draw different charts according to Excel table data, very detailed, with the same needs of small partners can refer to the following

This article shows that if you use Python to summarize commonly used charts, it is more cumbersome to draw a chart with Python than the Excel Point-of-action, especially when dealing with raw data. But the idea of both in charting is roughly the same, and most of the work that can be done in Excel is done in Python. For a clearer explanation of the process of drawing a chart using Python, we annotate the code in the summary chart to illustrate the specific role of each line of code. At the end of the article, the corresponding table of custom font and chart color is given.

Preparatory work


Import NumPy as Npimport pandas as pd# imports the chart library for chart drawing import Matplotlib.pyplot as PLTLOANDATA=PD. DataFrame (Pd.read_excel (' loan_data.xlsx '))


Line chart


#设置日期字段issue_d为loandata数据表索引字段loandata = Loandata.set_index (' issue_d ') #按月对贷款金额loan_amnt求均值, filling the null value with 0 loan_plot= loandata[' loan_amnt '].resample (' M '). Fillna (0) #图表字体为华文细黑, the font size is 15plt.rc (' font ', family= ' Stxihei ', size=15) # Create a one-dimensional array to assign values to Aa=np.array ([1,2,3,4,5,6,7,8,9,10,11,12]) #创建折线图, the data source is monthly loan mean, marker point, marker line style, line width, marker point color, and transparency Plt.plot (loan_ Plot, ' g^ ', Loan_plot, ' G ', color= ' #99CC01 ', linewidth=3,markeredgewidth=3,markeredgecolor= ' #99CC01 ', alpha=0.8) # Add x-axis label Plt.xlabel (' Month ') #添加y周标签plt. Ylabel (' Loan amount ') #添加图表标题plt. Title (' Distribution of monthly loan amount ') #添加图表网格线, set gridlines color, line, width and transparency Plt.grid ( Color= ' #95a5a6 ', linestyle= '--', linewidth=1, axis= ' y ', alpha=0.4 #设置数据分类名称plt. Xticks (A, (' January ', ' February ', ' March ', ' April ', ' May ', ' June ', ' July ', ' August ', ' September ', ' October ', ' November ', ' December ') #输出图表plt. Show ()


Bar chart


#按用户等级grade字段对贷款金额进行求和汇总loan_grade =loandata.groupby (' Grade ') [' loan_amnt '].agg (sum) #图表字体为华文细黑, the font size is 15plt.rc (' Font ', family= ' Stxihei ', size=15) #创建一个一维数组赋值给aa =np.array ([1,2,3,4,5,6]) #创建柱状图, the data source is the amount of the loan aggregated by user level, set the color, Transparency and outer border color Plt.bar ([1,2,3,4,5,6],loan_grade,color= ' #99CC01 ', alpha=0.8,align= ' center ', edgecolor= ' white ') # Set X-axis label Plt.xlabel (' User Level ') #设置y周标签plt. Ylabel (' Loan amount ') #设置图表标题plt. Title (' Distribution of loan amounts at different user levels ') #设置图例的文字和在图表中的位置plt. Legend ([ ' Loan amount ', loc= ' upper right ') #设置背景网格线的颜色, style, size and transparency Plt.grid (color= ' #95a5a6 ', linestyle= '--', linewidth=1,axis= ' y ', alpha=0.4) #设置数据分类名称plt. Xticks (A, (' Class A ', ' B ', ' C ', ' Class d ', ' e ', ' f ')) #显示图表plt. Show ()


Bar chart


#图表字体为华文细黑, the font size is 15plt.rc (' font ', family= ' Stxihei ', size=15) #创建一个一维数组赋值给aa =np.array ([1,2,3,4,5,6]) #创建条形图, The data source is aggregated for sub-level loan amounts, set color, transparency and chart border Plt.barh ([1,2,3,4,5,6],loan_grade,color= ' #99CC01 ', alpha=0.8,align= ' center ', edgecolor= ' white ') #添加x轴标题plt. Xlabel (' Loan amount ') #添加y轴标题plt. Ylabel (' User Level ') #添加图表标题plt. Title (' Distribution of loan amounts at different user levels ') #添加图例, and set the display position in the chart plt.legend ([' Loan amount '], loc= ' upper right ') #设置背景网格线的颜色, style, size and transparency Plt.grid (color= ' #95a5a6 ', linestyle= '--', Linewidth=1,axis= ' y ', alpha=0.4) #设置数据分类名称plt. Yticks (A, (' Class A ', ' B ', ' Class C ', ' d ', ' e ', ' f ') #显示图表plt. Show ()


Pie chart


#图表字体为华文细黑, the font size is 15plt.rc (' font ', family= ' Stxihei ', size=15) #设置饼图中每个数据分类的颜色colors = ["#99CC01", "#FFFF01", "#0000FE", "# FE0000 "," #A6A6A6 "," #D9E021 "] #设置饼图中每个数据分类的名称name =[' A-class ', ' B-class ', ' C-Class ', ' Class-d ', ' E-Class ', ' Class F '] #创建饼图, set the category label, color, and the starting position of the chart Plt.pie ( Loan_grade,labels=name,colors=colors,explode= (0, 0, 0.15, 0, 0, 0), startangle=60,autopct= '%1.1f%% ') #添加图表标题plt. Title (' Loan amount at different user levels ') #添加图例 and set the display location plt.legend ([' A ', ' B ', ' C ', ' d ', ' e ', ' f '], loc= ' upper left ') #显示图表plt. Show ()


Scatter chart


#按月汇总贷款金额, fill the null value with 0 loan_x=loandata[' loan_amnt '].resample (' M ', how=sum). Fillna (0) #按月汇总利息金额, with 0 padding null loan_y=loandata[' Total_rec_int '].resample (' M ', how=sum). Fillna (0) #图表字体为华文细黑, the font size is 15plt.rc (' font ', family= ' Stxihei ', size=15) #创建散点图, The loan amount is X, interest amount is Y, set color, mark dot style and transparency etc plt.scatter (loan_x,loan_y,60,color= ' white ', marker= ' o ', edgecolors= ' #0D8ECF ', linewidth=3,alpha=0.8) #添加x轴标题plt. Xlabel (' Loan amount ') #添加y轴标题plt. Ylabel (' interest income ') #添加图表标题plt. Title (' Loan Amount and Interest income ') # Set the color, style, size and transparency of the background gridlines Plt.grid (color= ' #95a5a6 ', linestyle= '--', linewidth=1,axis= ' both ', alpha=0.4) #显示图表plt. Show ()


Bubble chart


#按月汇总贷款金额及利息loan_x =loandata[' loan_amnt '].resample (' M ', how=sum). Fillna (0) loan_y=loandata[' total_rec_int ']. Resample (' m ', how=sum). Fillna (0) loan_z=loandata[' total_rec_int '].resample (' m ', how=sum). Fillna (0) #图表字体为华文细黑, The font size is 15plt.rc (' font ', family= ' Stxihei ', size=15) #设置气泡图颜色colors = ["#99CC01", "#FFFF01", "#0000FE", "#FE0000", "#A6A6A6", "#D9E021", ' #FFF16E ', ' #0D8ECF ', ' #FA4D3D ', ' #D2D2D2 ', ' #FFDE45 ', ' #9b59b6 '] #创建气泡图贷款金额为x, the interest amount is Y, and the interest amount is set to the bubble size, and set color transparency, and so on. Plt.scatter (loan_x,loan_y,s=loan_z,color=colors,alpha=0.6) #添加x轴标题plt. Xlabel (' Loan amount ') #添加y轴标题plt. Ylabel (' Interest income ') # Add Chart title plt.title (' Loan Amount and interest income ') #设置背景网格线的颜色, style, size and transparency Plt.grid (color= ' #95a5a6 ', linestyle= '--', linewidth=1,axis= ' Both ', alpha=0.4) #显示图表plt. Show ()


Box Line diagram


#图表字体为华文细黑, the font size is 15plt.rc (' font ', family= ' Stxihei ', size=15) #创建箱线图, the data source is the source of the loan, setting the horizontal display Plt.boxplot (loandata[' loan_amnt ') , 1, ' RS ', Vert=false) #添加x轴标题plt. Xlabel (' Loan amount ') #添加图表标题plt. Title (' Loan amount distribution ') #设置背景网格线的颜色, style, size and transparency Plt.grid (color= ' # 95a5a6 ', linestyle= '--', linewidth=1,axis= ' both ', alpha=0.4) #显示图表plt. Show ()


Histogram


#图表字体为华文细黑, the font size is 15plt.rc (' font ', family= ' Stxihei ', size=15) #创建直方图, the data source is the loan amount, the data is divided into 8 equal parts display, set the color and display mode, transparency and so on plt.hist ( loandata[' loan_amnt '],8,normed=1, histtype= ' stepfilled ', facecolor= ' #99CC01 ', rwidth=0.9,alpha=0.6,edgecolor= ' White ') #添加x轴标题plt. Xlabel (' Loan amount ') #添加y轴标题plt. Ylabel (' probability ') #添加图表标题plt. Title (' Loan amount probability density ') #设置背景网格线的颜色, style, Dimensions and Transparency Plt.grid (color= ' #95a5a6 ', linestyle= '--', linewidth=1,axis= ' y ', alpha=0.4) #显示图表plt. Show ()


Custom Fonts and Colors

The font used in the chart can be replaced with the following font name to change the font displayed in the chart family=.

Color in the chart, you can use the color name directly, or you can use the abbreviation to set the color used in the chart, instead of using the default color in this article, use a custom color.

The color number of the custom color, this article uses the hex color number, below gives the hex and the RGB correspondence relation, as well as the corresponding color. You can replace the color of the chart in this article with the following hex color number.

Related recommendations:

How to draw a line chart with Python

Example of drawing with Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.