在python中实现数据的可视化,也即作图,一般是依赖matplotlib宏包实现的。但常见的代码中都是加载pylab,是不是这里写错了呀?其实pylib只是matplotlib的一个模块,只是被做成了可以直接调用的形式,所以调用pylab实际上还是调用了matplotlib。pylab的绘图函数和参数名和matlab是非常类似的。鉴于输入法切换的麻烦,在例子源代码中的注释都使用了英文,这并不是从英文网站上拷贝过来的。

import pylab

基本设定

虽说pylab绘图和matlab很类似,但是也有不少的区别之处。

close all;clc;

在matlab作图中,开头最常见的一段就是这行命令,要在python中实现它,可以用下面的命令:

import os

# clc the terminal in ipython script, cls for windows, clear for linux/unix/mac
os.system('cls' if os.name == 'nt' else 'clear') # close all existing figure windows
pylab.close('all')

如果要进一步实现类似matlab的与图的动态交互,可以添加如下的命令:

# display figures interectively, which will not have to close figures to let the code run. Just like the way matlab plot works!
pylab.ion()

linestyles parameters

pylab.figure(1)
pylab.plot(x, y, linestyle='', linewidth=1, color='red', marker='*')
pylab.show()
['', ' ', 'None', '--', '-.', '-', ':']

小例子:控制字体和坐标点尺寸

# set the fontsize and ticklabel size
import pylab
import numpy pi=numpy.pi
x=numpy.linspace(0,1,100)
y=numpy.sin(2*pi*10*x) ax0=pylab.figure()
ax1=pylab.subplot(111)
pylab.plot(x,y,'-*',linewidth=2)
pylab.xlabel('x axis',fontsize=10,color='blue')
pylab.ylabel('y axis',fontsize=20)
pylab.grid('on')
pylab.title('test',fontsize=30)
# set parameters of tick markers
pylab.tick_params(which='major',labelsize=15,width=2,length=10,color='red')
pylab.tick_params(axis='x',colors='red')
pylab.tick_params(which='minor',width=1,length=5)
# control to show the minor tick
pylab.minorticks_on()
# control the color of axis line
ax1.spines['bottom'].set_color('green')
# control the color of ticklabel
pylab.tick_params(axis='x',color='green')
pylab.show()

设定图的尺寸大小[1]

pylab.figure(figsize=(20,10))
#pylab.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')
plot(x,y)
pylab.show()
# use tight layout if the text or edges of the figure are covered
fig.tight_layout()

在图中添加文字标记[2]

import numpy as np
import matplotlib.pyplot as plt fig = plt.figure()
ax = fig.add_subplot(111) t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2) ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05)) ax.set_ylim(-2,2)
plt.show()

隐藏legend的窗体[3]

#How to remove the box of the legend?
plt.legend(frameon=False)
#How to change the color of the border of the legend box?
leg = plt.legend()
leg.get_frame().set_edgecolor('b')
#How to remove only the border of the box of the legend?
leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

控制legend位置[5]

legend( ('label1', 'label2', 'label3'), loc='upper left')

add xlim, ylim

pylab.xlim([x1,x2])
pylab.ylim([y1,y2])

3D绘图并设置坐标轴等距

这里展示一个绘制三维空间曲线的例子,模型是托卡马克中的磁力线分布,其中matlabplotlib的equal axes设置在3D绘图中有缺陷,x,y轴等距离,但是z轴不会等距离,要实现相同的设置需要用到一些人为的设置,下面的代码中用的到设置函数set_axes_equal() 是在StackOverflow中的大神提供的[4]:

# this script will plot the magnetic field line with different q with circular cross section
import numpy
import pylab
from mpl_toolkits.mplot3d import Axes3D def set_axes_equal(ax):
'''Make axes of 3D plot have equal scale so that spheres appear as spheres,
cubes as cubes, etc.. This is one possible solution to Matplotlib's
ax.set_aspect('equal') and ax.axis('equal') not working for 3D. Input
ax: a matplotlib axis, e.g., as output from plt.gca().
'''
x_limits = ax.get_xlim3d()
y_limits = ax.get_ylim3d()
z_limits = ax.get_zlim3d()
x_range = abs(x_limits[1] - x_limits[0])
x_middle = numpy.mean(x_limits)
y_range = abs(y_limits[1] - y_limits[0])
y_middle = numpy.mean(y_limits)
z_range = abs(z_limits[1] - z_limits[0])
z_middle = numpy.mean(z_limits) # The plot bounding box is a sphere in the sense of the infinity
# norm, hence I call half the max range the plot radius.
plot_radius = 0.5*max([x_range, y_range, z_range])
ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])
ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])
ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius]) pylab.close()
pylab.ion()
pi=numpy.pi
q=2
R0=2 # big radius unit=m
a=0.3 # small radius unit=m
q=pi # safety factor # the parameter function of helix field structure in big cylinder coordinates is:
psi=numpy.linspace(0,10*2*pi,2000)
x=(R0+a*numpy.sin(q*psi))*numpy.cos(psi)
y=(R0+a*numpy.sin(q*psi))*numpy.sin(psi)
z=a*numpy.cos(q*psi) fig1=pylab.figure()
ax=Axes3D(fig1)
ax.plot3D(x,y,z)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
# set equal axes length unit
ax.axis('equal')
# apply the function to set equal axis on x,y,z axis
set_axes_equal(ax)
pylab.show()

模拟的结果:

  1. 变换坐标轴数字为科学计数显示
fig=pylab.figure()
ax1=fig.add_subplot(111)
ax1.plot(R_half,B_half)
pylab.legend(['possitive B(R) distribution'])
pylab.xlim([0,2.3])
pylab.minorticks_on()
pylab.xlabel('R')
pylab.ylabel('B(T)')
ax1.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e'))
# 1e means how many rank is kept after decimal point.

注意,需要单独再定义一个subplot是因为ax=pylab.plot(x,y)得到的ax不是图形对象,而只是一个list,所以无法更改axis显示模式。因此需要再使用subplot获得一个对象。

  1. 对所有图的对象进行统一的字体设定
import matplotlib
import pylab
fig=pylab.figure()
ax1=fig.add_subplot(111)
ax1.plot(x,y)
pylab.legend(['test',])
pylab.title('test')
pylab.xlabel('X label')
pylab.ylabel('Y label')
matplotlib.rcParms.update({'font.size':15})
  1. 绘制箭头
# draw an arrow in the figure
import pylab
import numpy
pi=numpy.pi
x=numpy.linspace(0,6,50)
y=numpy.sin(x)
x0=0.1
y0=0.3
angle=45.0/180.0*pi
r0=1
pylab.figure()
pylab.plot(x,y)
pylab.hold('on')
pylab.arrow(x0,y0,r0*numpy.cos(angle),r0*numpy.sin(angle),r0,linewidth=2,width=0.005,color='red',linestyle=':')
pylab.axis('equal')
pylab.show()

其中width单独控制了箭头的大小

参考:

[1]: Stackoverflow: https://stackoverflow.com/questions/332289/how-do-you-change-the-size-of-figures-drawn-with-matplotlib

[2]: https://matplotlib.org/users/annotations_intro.html

[3]: Stackoverflow: https://stackoverflow.com/questions/25540259/remove-or-adapt-border-of-frame-of-legend-using-matplotlib

[4]: https://stackoverflow.com/questions/13685386/matplotlib-equal-unit-length-with-equal-aspect-ratio-z-axis-is-not-equal-to

[5]: https://stackoverflow.com/questions/10824156/matplotlib-legend-location-numbers

Python: 作图的更多相关文章

  1. Matlab vs Python 作图

    -- Matlab 作图示例 x=-3:0.00003:3; y1=sin(x)./x; y2=x./sin(x); plot(x,y1,x,y2); -- Python 作图示例 import nu ...

  2. 揽货最短路径解决方案算法 - V2(增加了时间维度-客户允许的服务时间段,C#/JAVA同步实现,带python作图)

    继上篇,这里改进增加了客户允许服务的时间范围这个维度,并且把C#版本翻译成java,加强了更加形象的图表展示路径(继续是用python的matplotlib作图). 这里的时间范围维度是指:每个客户都 ...

  3. Python作图笔记

    感谢莫烦大神,附带他的个人网站链接:https://morvanzhou.github.io/ 再带上官方的文档,多看文档啊!不然参数忘了就没地方查了:https://matplotlib.org/a ...

  4. Python作图包含type3字体解决方案

    1. 解决方案 matplotlib.rcParams[‘text.usetex’] = True

  5. Python中的高级turtle(海龟)作图(续)

    四.填色 color 函数有三个参数.第一个参数指定有多少红色,第二个指定有多少绿色,第三个指定有多少蓝色.比如,要得到车子的亮红色,我们用 color(1,0,0),也就是让海龟用百分之百的红色画笔 ...

  6. 【python】Matplotlib作图常用marker类型、线型和颜色

    python作图中常常会考虑用什么颜色.marker.线型,这个资料查了又查,所以自己总结在这个地方,以便常用. 一.常用marker表示 1.普通marker 这类普通marker直接marker ...

  7. python数据分析开发中的常用整理

    Pandas操作 python使用pandas读取csv import pandas as pd #数据筛选 usetTable = pd.read_csv(filename,header = 0) ...

  8. DocNan博文目录

    算法 时频分析:窗口傅立叶变换 数学误区:乘积的求和 MHD simulation with python Linux Linux: Bash基本命令 Linux: 安装和启用firefox浏览器的j ...

  9. BX谷 2019年最新所有人都能学会的数据分析课视频教程

    第一章 数据分析师职业概览 1-1 数据分析师的职业概览免费试学 数据分析师的"钱"景如何 什么人适合学数据分析 数据分析师的临界知识 数据分析师的主要职责 第二章 数据分析和数据 ...

随机推荐

  1. 初识Celery

    本系列文章的开发环境: window + python2. + pycharm5 + celery3.1.25 + django1.9.4 在我们日常的开发工作中,经常会遇到这几种情况: 1.在web ...

  2. MyEclipse2016添加外部的maven插件

    1.在maven官网下载最新的maven安装包,下载地址:http://maven.apache.org/download.cgi: 2.目前maven的版本是3.5.0,我们下载apache-mav ...

  3. Hbuilder常用功能汇总

    引用 样式表: mui.min.css Js:mui.min.js 常用功能 获取页面 var webView=plus.webview.currentWebview();//获取当前页 var we ...

  4. VR全景智慧城市

    随着虚拟现实产业的发展,我国对虚拟现实产业也越来越重视了.我国虚拟现实VR市场增长速度很快,市场活跃性很高,很多人都看好我国的虚拟现实VR市场,而且未来国内虚拟现实VR市场的销量还将有更大的增长.据赛 ...

  5. python serialread

    代码易读,不再做注释 import serial,os port = os.popen('ls /dev/ttyACM*').read()[:-1] baud = 9600 ser = serial. ...

  6. 简易数据加密传输电路(VHDL)(原创)

    LIBRARY IEEE; USE IEEE.STD_LOGIC_1164.ALL; USE IEEE.std_logic_unsigned.ALL; ENTITY KEKE IS --定义实体wsj ...

  7. JBoss7安装、测试、配置和启动以及停止,部署

    转:http://www.hongyanliren.com/2014m01/3013.html 内容概要 JBoss系列三主要目的是演示如何部署应用到JBoss7/WildFly,如下图中描述了部署应 ...

  8. 【对抗蠕虫】如何保护网页里的按钮,不被 XSS 自动点击

    前言 XSS 自动点按钮有什么危害? 在社交网络里,大多操作都是通过点击按钮发起的.例如发表留言,假如留言系统有 BUG,那么 XSS 就能自动点击发送按钮,发布带有恶意代码的留言.好友看了中招后,又 ...

  9. Lambda应用场景和使用实例

    Java 8已经推出一段时间了,Lambda是其中最火的主题,不仅仅是因为语法的改变,更重要的是带来了函数式编程的思想.这篇文章主要聊聊Lambda的应用场景及其相关使用示例. Java为何需要Lam ...

  10. ajax传数组到后台,后台springmvc接收数组参数

    var   ids= new Array();  $("input[class='detailCheck']:checked").each(function(i,k){   var ...