Python画图——基础篇
- 1 前言
- 2 matplotlib
- 2.1 画直线图
- 2.2画散点图
- 2.3 区域填充
- 2.4 坐标轴相关
- 2.4.1 坐标轴范围
- 2.4.2 坐标轴刻度
- 2.4.3 坐标轴标签
- 2.4.4 隐藏坐标轴
- 2.5 标题
- 2.6 画布设置
- 2.7 保存文件
- 2.8 实例
- 3 pygal
- 3.1 直方图
- 3.2 折线图
- 3.3 管理生成的svg图
1 前言
本文章基于《Python编程,从入门到实践》,Eric Matthes著。书中采用的是matplotlib库和pygal库。我的配置为anaconda下python3.7.1,由于目前pygal官方未提供python3.7版本,故创建了python3.5环境。
文章会将画图从零讲起,如果您有一定的基础,或想绘制非常炫酷的图像,请访问matplotlib官网或pygal官网查看更多。也可以查看我的另一篇文档python画图——进阶篇(预计2019/5/8发布)
2 matplotlib
matplotlib.pyplot是一个命令型函数集合,包含了众多的函数,这些函数可以控制画布,让使用者如使用matlab一样方便地进行绘图。
在使用前,需要导入该库,一般简写为plt。
import matplotlib.pyplot as plt
2.1 画直线图
// draw a line
plt.plot(array_x,array_y,options)
可选项options包括:
- x坐标:array_x为可选项,为数组时即为x轴坐标主刻度,不写时默认生成0,1,2,3……
- 线宽:linewith=n
- 线透明度:alpha=(0,1),越接近0,透明度越大
2.2画散点图
// draw a scatter
plt.scatter(array_x,array_y,options)
// draw a series of points with options
array_x=['1','2','3','4','5']
array_y=['1','4','9','16','25']
plt.scatter(array_x,array_y,s=15,edgecolor='pink',c=y,cmap=plt.cm.cool)
plt.show()
可选项options包括:
- 点大小:s=d
- 去除边缘:edgecolor=‘none’
- 改变点颜色(默认为蓝色):c=‘color’,还可使用c=(r,g,b),其中r/g/b取0~1之间,程序运行会报警告,但可以继续使用
- 颜色映射:将c设置为y数组,cmap=plt.cm.映射模式,matplotlib官网提供了大量颜色映射模式,颜色映射可以使可视化效果更好
2.3 区域填充
// fill the region that between two lines
plt.fill_between(array_x,array_y1,array_y2,options)
可选项options包括:
- 填充区域颜色:facecolor=‘color’
- 填充区透明度:alpha=(0,1),越接近0,透明度越大
2.4 坐标轴相关
2.4.1 坐标轴范围
plt.axis([x0,xt,y0,yt])
x0表示x标轴起始x坐标;xt表示x轴最后一个x坐标
y0表示y标轴起始y坐标;yt表示y轴最后一个y坐标
// create a tuple variable as x/y scale
plt.xlim((a,b))
plt.ylim((a,b))
// create an array variable as x/y scale
plt.xticks(array_x)
plt.yticks(array_y)
// create a mapping between an numeric array and a literal array
plt.xticks(array_x,words_x)
上述命令分别生成x/y轴的刻度,内容分别为元组/数组/文字
2.4.2 坐标轴刻度
plt.tick_params(options)
可选项options包括:
- 刻度字体大小:labelsize=n
- 显示主刻度,副刻度:which='major/minor/both,默认major
- 应用范围(x/y坐标轴):axis=‘x/y/both’,默认both
2.4.3 坐标轴标签
plt.xlabel("",options)
plt.ylabel("",options)
fig.autofmt_xdate() // plt.gcf().autofmt_xdate()
// transform date
import datetime from datetime // you need import this first
date=datetime.strptime(d,"%Y-%m-%d")
可选项options包括:
- 字体大小:fontsize=n
- 以斜体/日期格式显示x轴刻度标签:fig.autofmt_xdate()或plt.gcf().autofmt_xdate(),在这之前需要转化日期,如上
2.4.4 隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
注意此命令需要用在plt.show()之前,不然会报错,因为plt.show()创建了一个画布
如果想先看到结果,可以首先实例化一个fig,调用fig的show()函数
2.5 标题
plt.title("",options)
可选项options包括:
- 字体大小:fontsize=n
2.6 画布设置
fig=plt.figure(dpi=xxx,figsize=(width,height))
dpi是规定像素质量,即每英寸多少个像素,一般不写即为默认值
figsize是生成的图片大小,单位是英寸
2.7 保存文件
plt.savefig('figname.xxx',options)
可选项options包括:
- figname的拓展名:可以是jpg/jpeg/png等
- 保存时是否删除图片周围的空白区域:bbox_inches=‘tight’
2.8 实例
示例内容为使用matplotlib.pyplot完成的随机漫步
from random import choice
import matplotlib.pyplot as plt
class RandomWalk():
"""创建随即漫步类"""
def __init__(self,num_points=5000):
self.num_points=num_points
self.x_values=[0] //用于放置x数组
self.y_values=[0] //用于放置y数组
def fill_walk(self):
while len(self.x_values)<self.num_points:
x_direction=choice([1,-1])
x_distance=choice([0,1,2,3,4])
x_step=x_direction*x_distance //创建x的步进
y_direction=choice([1,-1])
y_distance=choice([0,1,2,3,4])
y_step=y_direction*y_distance //创建y的步进
if x_step==0 and y_step==0: //如果原地不动,则跳过,重新生成
continue
next_x=self.x_values[-1]+x_step
next_y=self.y_values[-1]+y_step
self.x_values.append(next_x)
self.y_values.append(next_y) //创建了两个数组,存储xy的步进值
while True:
rw=RandomWalk(50000) //创建一个生成5w个点的实例
rw.fill_walk() //进行随即漫步
plt.figure(figsize=(10,6)) //设置画布大小
point_numbers=list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,s=1,c=point_numbers,cmap=plt.cm.cool) //绘制各点,并且使用映射效果cool
plt.scatter(0,0,c='green',edgecolors='none',s=50) //将初始点突出显示
plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=50) //将末尾点突出显示
plt.axes().get_xaxis().set_visible(False) //隐藏x轴
plt.axes().get_yaxis().set_visible(False) //隐藏y轴
plt.show()
keep_running=input("Make another walk?(Y/N)")
if keep_running=='N':
break
3 pygal
pygal可以生成可缩放的矢量图,一般保存文件格式为svg
使用pygal前,需要导入pygal包。了解更多关于pygal,可以访问pygal官网
import pygal
3.1 直方图
hist=pygal.Bar(options)
hist.title=""
hist.x_labels=['1','2','3','4','5']
hist.x_title=""
hist.y_title=""
hist.add('name',array_y)
hist.render_to_file('xxx.svg')
hist.title=:完成了直方图标题的规定
hist.x_labels=[]:x轴显示的内容
hist.x_title/hist.y_title:规定x/y轴的标题
hist.add(‘name’,array_y):将数组array_y即值加入图片,图例为name
hist.render_to_file(‘name.svg’):保存为svg文件,使用浏览器打开
pygal.Bar()可选项为:
- 样式:style=my_style,其中my_style由pygal.style.LightenStyle设置,如my_style=LS(’#333366’,base_style=LCS);LCS是pygal.style.LightColorizedStyle库,这个语句表示设置直方图的样式为LCS默认样式,填充颜色为蓝色
- 标签旋转:x_label_rotation=angle
- 隐藏图例:show_legend=False
可以使用pygal.Config()创建一个实例,来更改坐标轴的其他参数
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
my_style=LS('#333366',base_style=LCS)
my_config=pygal.Config() // create a new style
my_config.x_label_rotation=45 // rotate 45 degrees clockwise for x labels
my_config.show_legend=False // hide the legend
my_config.title_font_size=24 // set fontsize of title
my_config.label_font_size=14 // set fontsize of labels
my_config.major_label_font_size=18 // set fontsize of major labels
my_config.truncate_label=15 // limit the repository's name below 15 words, you can check it in svg file when your mouse moves on it
my_config.show_y_guides=False // hide the y grid
my_config.width=1000 // the width of figure
chart=pygal.Bar(my_config,style=my_style)
在交互方面,如果不设置其他参数,将鼠标放置在直方图上时,会显示数值,若要添加描述,可以向bar.add()函数提供一个字典列表,此外,还可以加入链接,即当点击该直方图时,可以转到对应的网页
dicts=[{'value':1,'label':one},{'value':2,'label':two},{'value':3,'label':three}]
//dicts=[{'value':1,'label':one,'xlink':url_1},{'value':2,'label':two,'xlink':url_2},{'value':3,'label':three,'xlink':url_3}]
chart.add('',dicts)
3.2 折线图
line=pygal.Line(options)
line.title=""
line.x_labels=array
line.x_labels_major=array[::N] // label with an inteval N
line.add('name',array_y)
其中,pygal.LIne()的可选项包括:
- x坐标轴标签顺时针旋转角度:x_label_rotation=angle
- 不显示x轴标签的所有值:show_minor_x_labels=False
3.3 管理生成的svg图
with open('Dashboard.html','w',encoding='utf8') as html_file:
html_file.write('<html><head><title>Dashboard</title><meta charset="utf-8"></head><body>\n')
for svg in svg_list:
html_file.write(' <object type="image/svg+xml" data="{0}" height=500></object>\n'.format(svg))
html_file.write('</body></html>')
这样就可以在生成的html网页中查看自己的svg图