Home Backend Development Python Tutorial Draw commonly used charts using python

Draw commonly used charts using python

Apr 24, 2018 pm 02:58 PM
python chart use

This article introduces how to use Python to draw different charts based on Excel table data. It is very detailed. Friends who have the same needs can refer to it.

This article introduces how to use Python to summarize commonly used Charts, compared with the click-and-click operation of Excel, drawing charts with python seems more cumbersome, especially in the processing of original data. However, the two have roughly the same idea in the process of drawing charts. Most of the work that can be done in Excel can also be done by python. In order to explain more clearly the process of drawing charts using python, we annotate the code of the summary chart to explain the specific function of each line of code. At the end of the article, a corresponding table of custom fonts and chart colors is given.

Preparation


import numpy as np
import pandas as pd
#导入图表库以进行图表绘制
import matplotlib.pyplot as plt
loandata=pd.DataFrame(pd.read_excel('loan_data.xlsx'))
Copy after login


Line chart


#设置日期字段issue_d为loandata数据表索引字段
loandata = loandata.set_index('issue_d')
#按月对贷款金额loan_amnt求均值,以0填充空值
loan_plot=loandata['loan_amnt'].resample('M').fillna(0)
#图表字体为华文细黑,字号为15
plt.rc('font', family='STXihei', size=15)
#创建一个一维数组赋值给a
a=np.array([1,2,3,4,5,6,7,8,9,10,11,12])
#创建折线图,数据源为按月贷款均值,标记点,标记线样式,线条宽度,标记点颜色和透明度
plt.plot(loan_plot,'g^',loan_plot,'g-',color='#99CC01',linewidth=3,markeredgewidth=3,markeredgecolor='#99CC01',alpha=0.8)
#添加x轴标签
plt.xlabel('月份')
#添加y周标签
plt.ylabel('贷款金额')
#添加图表标题
plt.title('分月贷款金额分布')
#添加图表网格线,设置网格线颜色,线形,宽度和透明度
plt.grid( color='#95a5a6',linestyle='--', linewidth=1 ,axis='y',alpha=0.4)
#设置数据分类名称
plt.xticks(a, ('1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月') )
#输出图表
plt.show()
Copy after login


Bar chart


#按用户等级grade字段对贷款金额进行求和汇总
loan_grade=loandata.groupby('grade')['loan_amnt'].agg(sum)
#图表字体为华文细黑,字号为15
plt.rc('font', family='STXihei', size=15)
#创建一个一维数组赋值给a
a=np.array([1,2,3,4,5,6])
#创建柱状图,数据源为按用户等级汇总的贷款金额,设置颜色,透明度和外边框颜色
plt.bar([1,2,3,4,5,6],loan_grade,color='#99CC01',alpha=0.8,align='center',edgecolor='white')
#设置x轴标签
plt.xlabel('用户等级')
#设置y周标签
plt.ylabel('贷款金额')
#设置图表标题
plt.title('不同用户等级的贷款金额分布')
#设置图例的文字和在图表中的位置
plt.legend(['贷款金额'], loc='upper right')
#设置背景网格线的颜色,样式,尺寸和透明度
plt.grid(color='#95a5a6',linestyle='--', linewidth=1,axis='y',alpha=0.4)
#设置数据分类名称
plt.xticks(a,('A级','B级','C级','D级','E级','F级'))
#显示图表
plt.show()
Copy after login


##Bar chart


#图表字体为华文细黑,字号为15
plt.rc('font', family='STXihei', size=15)
#创建一个一维数组赋值给a
a=np.array([1,2,3,4,5,6])
#创建条形图,数据源为分等级贷款金额汇总,设置颜色,透明度和图表边框
plt.barh([1,2,3,4,5,6],loan_grade,color='#99CC01',alpha=0.8,align='center',edgecolor='white')
#添加x轴标题
plt.xlabel('贷款金额')
#添加y轴标题
plt.ylabel('用户等级')
#添加图表标题
plt.title('不同用户等级的贷款金额分布')
#添加图例,并设置在图表中的显示位置
plt.legend(['贷款金额'], loc='upper right')
#设置背景网格线的颜色,样式,尺寸和透明度
plt.grid(color='#95a5a6',linestyle='--', linewidth=1,axis='y',alpha=0.4)
#设置数据分类名称
plt.yticks(a,('A级','B级','C级','D级','E级','F级'))
#显示图表
plt.show()
Copy after login


##pie chart

#图表字体为华文细黑,字号为15
plt.rc('font', family='STXihei', size=15)
#设置饼图中每个数据分类的颜色
colors = ["#99CC01","#FFFF01","#0000FE","#FE0000","#A6A6A6","#D9E021"]
#设置饼图中每个数据分类的名称
name=['A级', 'B级', 'C级', 'D级', 'E级','F级']
#创建饼图,设置分类标签,颜色和图表起始位置等
plt.pie(loan_grade,labels=name,colors=colors,explode=(0, 0, 0.15, 0, 0, 0),startangle=60,autopct='%1.1f%%')
#添加图表标题
plt.title('不同用户等级的贷款金额占比')
#添加图例,并设置显示位置
plt.legend(['A级','B级','C级','D级','E级','F级'], loc='upper left')
#显示图表
plt.show()
Copy after login


Scatter plot

#按月汇总贷款金额,以0填充空值
loan_x=loandata['loan_amnt'].resample('M',how=sum).fillna(0)
#按月汇总利息金额,以0填充空值
loan_y=loandata['total_rec_int'].resample('M',how=sum).fillna(0)
#图表字体为华文细黑,字号为15
plt.rc('font', family='STXihei', size=15)
#创建散点图,贷款金额为x,利息金额为y,设置颜色,标记点样式和透明度等
plt.scatter(loan_x,loan_y,60,color='white',marker='o',edgecolors='#0D8ECF',linewidth=3,alpha=0.8)
#添加x轴标题
plt.xlabel('贷款金额')
#添加y轴标题
plt.ylabel('利息收入')
#添加图表标题
plt.title('贷款金额与利息收入')
#设置背景网格线的颜色,样式,尺寸和透明度
plt.grid(color='#95a5a6',linestyle='--', linewidth=1,axis='both',alpha=0.4)
#显示图表
plt.show()
Copy after login


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)
#图表字体为华文细黑,字号为15
plt.rc('font', family='STXihei', size=15)
#设置气泡图颜色
colors = ["#99CC01","#FFFF01","#0000FE","#FE0000","#A6A6A6","#D9E021",'#FFF16E','#0D8ECF','#FA4D3D','#D2D2D2','#FFDE45','#9b59b6']
#创建气泡图贷款金额为x,利息金额为y,同时设置利息金额为气泡大小,并设置颜色透明度等。
plt.scatter(loan_x,loan_y,s=loan_z,color=colors,alpha=0.6)
#添加x轴标题
plt.xlabel('贷款金额')
#添加y轴标题
plt.ylabel('利息收入')
#添加图表标题
plt.title('贷款金额与利息收入')
#设置背景网格线的颜色,样式,尺寸和透明度
plt.grid(color='#95a5a6',linestyle='--', linewidth=1,axis='both',alpha=0.4)
#显示图表
plt.show()
Copy after login


Boxplot

#图表字体为华文细黑,字号为15
plt.rc('font', family='STXihei', size=15)
#创建箱线图,数据源为贷款来源,设置横向显示
plt.boxplot(loandata['loan_amnt'],1,'rs',vert=False)
#添加x轴标题
plt.xlabel('贷款金额')
#添加图表标题
plt.title('贷款金额分布')
#设置背景网格线的颜色,样式,尺寸和透明度
plt.grid(color='#95a5a6',linestyle='--', linewidth=1,axis='both',alpha=0.4)
#显示图表
plt.show()
Copy after login


##Histogram

#图表字体为华文细黑,字号为15
plt.rc('font', family='STXihei', size=15)
#创建直方图,数据源为贷款金额,将数据分为8等份显示,设置颜色和显示方式,透明度等
plt.hist(loandata['loan_amnt'],8,normed=1, histtype='stepfilled',facecolor='#99CC01', rwidth=0.9,alpha=0.6,edgecolor='white')
#添加x轴标题
plt.xlabel('贷款金额')
#添加y轴标题
plt.ylabel('概率')
#添加图表标题
plt.title('贷款金额概率密度')
#设置背景网格线的颜色,样式,尺寸和透明度
plt.grid(color='#95a5a6',linestyle='--', linewidth=1,axis='y',alpha=0.4)
#显示图表
plt.show()
Copy after login



Custom fonts and colors

used in charts Font, you can use the following font name to replace the content after family= to change the font displayed in the chart.

For the colors in the chart, you can use the color name directly, or you can use the abbreviation to set the color used in the chart. This article does not use the default color, but uses Custom colors.

The color number of custom colors. The Hex color number is used in this article. The corresponding relationship between Hex and RGB, as well as the corresponding colors, are given below. You can use the Hex color numbers below to replace the colors of the charts in this article.

Related recommendations:

How to use python to draw a line chart

Use python to draw graphics Detailed explanation of examples

The above is the detailed content of Draw commonly used charts using python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles