本文为学习笔记----总结!大部分为demo。一部分为学习中遇到的问题总结。包含怎么设置标签为中文等。matlab博大精深。须要用的时候再继续吧。

Pyplot tutorial

Demo地址为:点击打开链接 
一个简单的样例:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
plt.plot([1, 4, 9, 16])
plt.ylabel('some numbers')
plt.show()

执行结果为:

我仅仅指定了一组list參数。从图中能够看书,这组參数自己主动分配为了纵坐标。为什么会这样呢?

你可能想知道为什么X轴的范围是0-3。假设你提供一个单一的列表或数组的plot()命令,matplotlib假定这是一个序列的y值,并自己主动生成X值。

由于Python范围从0開始,默认x向量从0開始并以1为步长自己主动得到X坐标。

因此X的数据为[ 0, 1, 2, 3 ]。

plot()是一种通用的命令,并将採取随意数量的參数。默认X和Y的參数为list(实际上内部都是转化为数组numpy)。而且长度同样,否则报错。

For every x, y pair of arguments, there is an optional third argument which is the format string
that indicates the color and line type of the plot. The letters and symbols of the format string are from MATLAB, and you concatenate a color string with a line style string. The default format string is ‘b-‘, which is a solid blue line. For example, to plot
the above with red circles, you would issue

对于每个X,Y參数对,有一个可选的第三个參数是表示颜色的和线型的格式字符串。

格式字符串的字母和符号来源于MATLAB。你能够制定颜色和线型。

默认的格式字符串为“b-”,这是一个蓝线实线。

如上图所看到的。

plot() 文档有完整的格式化字符串參数说明。axis() 命令指定坐标范围[xmin, xmax, ymin, ymax]。

样例:

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt # evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

结果为:

Controlling line properties

Lines have many attributes that you can set: linewidth线宽, dash style, antialiased抗锯齿, etc;
see matplotlib.lines.Line2D.
There are several ways to set line properties
1、利用keyword:
plt.plot(x, y, linewidth=2.0)

2、利用setter方法

line1, line2 = plot(x1,y1,x2,y2)
line.set_antialiased(False) # turn off antialising

3、使用 setp() 命令

lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

Here
are the available Line2D properties.



4、To get a list of settable line properties, call the setp() function
with a line or lines as argument
比如:
lines = plt.plot([1,2,3])

plt.setp(lines)
alpha: float
animated: [True | False]
antialiased or aa: [True | False]
...snip

以上为调用setp()第二种方法。

Working with multiple figures and axes

MATLAB, and pyplot,
have the concept of the current figure and the current axes. All plotting commands apply to the current axes. The function gca() returns
the current axes (amatplotlib.axes.Axes instance),
and gcf() returns
the current figure (matplotlib.figure.Figure instance).
Normally, you don’t have to worry about this, because it is all taken care of behind the scenes. Below is a script to create two subplots.

MATLAB和pyplot,有当前图和当前轴的概念。全部的画图命令适用于当前轴。

gca()方法返回当前轴(一个matplotlib.axes.axes实例)。和gcf()方法返回当前图形(matplotlib.figure.figure实例)。通常,你不用操心这个,由于它是幕后自己主动管理的。以下是一个脚本来创建两个图。

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt def f(t):
return np.exp(-t) * np.cos(2*np.pi*t) t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02) plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

结果为:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhbmgxMjE4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">

The figure() command
here is optional because figure(1) will
be created by default, just as a subplot(111) will
be created by default if you don’t manually specify an axes. Thesubplot() command
specifies numrows, numcols, fignum where fignum ranges
from 1 to numrows*numcols.
The commas in the subplot command
are optional if numrows*numcols<10.
Sosubplot(211) is
identical to subplot(2,1,1).
You can create an arbitrary number of subplots and axes. If you want to place an axes manually, ie, not on a rectangular grid, use theaxes() command,
which allows you to specify the location as axes([left, bottom, width, height]) where
all values are in fractional (0 to 1) coordinates. See pylab_examples
example code: axes_demo.py
 for an example of placing axes manually and pylab_examples
example code: line_styles.py
 for an example with lots-o-subplots.

You can create multiple figures by using multiple figure() calls
with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires:

这里的figure()指令是可选的由于figure(1)默认会被创建,就像subplot(111)将默认创建当你不手动指定axes的情况下。该subplot()命令指定numrows,numcols,fignum范围从1到numrows
* numcols【即211为2行1列第1幅图。和MATLAB同样】。

假设numrows * numcols<10,subplot()命令中的逗号是可选的。您能够创建随意数量的subplots和axes。假设你想手动设置一个axes,能够使用axes()命令,它同意你指定的位置为axes([left, bottom, width, height])。全部的值都是分数(0~1)坐标。

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
plt.figure(1) # the first figure
plt.subplot(211) # the first subplot in the first figure
plt.plot([1,2,3])
plt.subplot(212) # the second subplot in the first figure
plt.plot([4,5,6]) plt.figure(2) # a second figure
plt.plot([4,5,6]) # creates a subplot(111) by default plt.figure(1) # figure 1 current; subplot(212) still current
plt.subplot(211) # make subplot(211) in figure1 current
plt.title('Easy as 1,2,3') # subplot 211 title
plt.show()

You can clear the current figure with clf() and
the current axes with cla().
If you find this statefulness, annoying, don’t despair, this is just a thin stateful wrapper around an object oriented API, which you can use instead (see Artist
tutorial
)

If you are making a long sequence of figures, you need to be aware of one more thing: the memory required for a figure is not completely released until the figure is explicitly closed with close().
Deleting all references to the figure, and/or using the window manager to kill the window in which the figure appears on the screen, is not enough, because pyplot maintains internal references until close() is
called.

Working with text

The text() command
can be used to add text in an arbitrary location, and the xlabel()ylabel() and title() are
used to add text in the indicated locations (see Text
introduction
 for a more detailed example)

加入标签!怎么加入中文标签?!

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000) # the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts')
plt.ylabel(u'概率', fontproperties='SimHei')
plt.title(u'IQ直方图', fontproperties='SimHei')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

结果例如以下所看到的:

All of the text() commands
return an matplotlib.text.Text instance.
Just as with with lines above, you can customize the properties by passing keyword arguments into the text functions or using setp():

t = plt.xlabel('my data', fontsize=14, color='red')

These properties are covered in more detail in Text properties and layout.

Using mathematical expressions in text

在文本中使用的数学表达式。matplotlib accepts TeX equation
expressions in any text expression. For example to write the expression  in
the title, you can write a TeX expression surrounded by dollar signs:

plt.title(r'$\sigma_i=15$')

The r preceding
the title string is important – it signifies that the string is a raw string and not to treat backslashes and python escapes. matplotlib has a built-in TeX expression parser and layout engine, and ships its own math fonts – for details see Writing
mathematical expressions
. Thus you can use mathematical text across platforms without requiring a TeX installation. For those who have LaTeX and dvipng installed, you can also use LaTeX to format your text and incorporate the output directly into
your display figures or saved postscript – see Text rendering With LaTeX.

Annotating text

The uses of the basic text() command
above place text at an arbitrary position on the Axes. A common use case of text is to annotate some feature of the plot, and the annotate()method
provides helper functionality to make annotations easy. In an annotation, there are two points to consider: the location being annotated represented by the argument xy and
the location of the text xytext.
Both of these arguments are (x,y) tuples.

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

结果为:




In
this basic example, both the xy (arrow
tip) and xytext locations
(text location) are in data coordinates. There are a variety of other coordinate systems one can choose – seeAnnotating
text
 and Annotating
Axes
 for details. More examples can be found in pylab_examples
example code: annotation_demo.py
.

其它

这部分内容详细请看:点击打开链接

横向图形:

from matplotlib import pyplot as plt
from numpy import sin, exp, absolute, pi, arange
from numpy.random import normal def f(t):
s1 = sin(2 * pi * t)
e1 = exp(-t)
return absolute((s1 * e1)) + .05 t = arange(0.0, 5.0, 0.1)
s = f(t)
nse = normal(0.0, 0.3, t.shape) * s fig = plt.figure(figsize=(12, 6))
vax = fig.add_subplot(121)
hax = fig.add_subplot(122) vax.plot(t, s + nse, 'b^')
vax.vlines(t, [0], s)
vax.set_xlabel('time (s)')
vax.set_title('Vertical lines demo') hax.plot(s + nse, t, 'b^')
hax.hlines(t, [0], s, lw=2)
hax.set_xlabel('time (s)')
hax.set_title('Horizontal lines demo') plt.show()

结果为:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhbmgxMjE4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">

点状分布图:

import numpy as np
import matplotlib.pyplot as plt N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses plt.scatter(x, y, s=area, alpha=0.5)
plt.show()

结果为:




总结

1、颜色控制:

b:blue ,c:cyan,g:green,k:black,m:magenta。r:red ,w:white,
y:yellow。

控制颜色方法:
简称或者全称:如上所列。
16进制:FF00FF;
RGB或RGBA元组:(1,0,1,1);
灰度强度如:0.7;(大量颜色处理适用。不反复的随机数就可以)

2、线型控制:

-     
实线;    --     短线;    -.     短点相间线。    :    
虚点线

3、点的标记

hatch [‘/’ | ‘\’ | ‘|’ | ‘-‘ | ‘+’ | ‘x’ | ‘o’ | ‘O’ | ‘.’ | ‘*’]

Point marker

,  Pixel marker

o  Circle marker

v  Triangle down marker 

^  Triangle up marker 

<  Triangle left marker 

>  Triangle right marker 

1  Tripod down marker

2  Tripod up marker

3  Tripod left marker

4  Tripod right marker

s  Square marker

p  Pentagon marker

*  Star marker

h  Hexagon marker

H  Rotated hexagon D Diamond marker

d  Thin diamond marker

|    Vertical line (vlinesymbol) marker

_  Horizontal line (hline symbol) marker

+  Plus marker

x  Cross (x) marker
以上部分内容来源于:点击打开链接

未完待续。

。随时更新。

欢迎提问。共同学习,一起进步。

本文由@The_Third_Wave(Blog地址:http://blog.csdn.net/zhanh1218)原创。不定期更新,有错误请指正。

Sina微博关注:@The_Third_Wave

假设这篇博文对您有帮助。为了好的网络环境,不建议转载,建议收藏!假设您一定要转载。请带上后缀和本文地址。

Python:2D画图库matplotlib学习总结的更多相关文章

  1. 推荐:python科学计算pandas/python画图库matplotlib【转】

    机器学习基础3--python科学计算pandas(上) 地址:https://wangyeming.github.io/2018/09/04/marchine-learning-base-panda ...

  2. 『科学计算』科学绘图库matplotlib学习之绘制动画

    基础 1.matplotlib绘图函数接收两个等长list,第一个作为集合x坐标,第二个作为集合y坐标 2.基本函数: animation.FuncAnimation(fig, update_poin ...

  3. Python第三方库matplotlib(2D绘图库)入门与进阶

    Matplotlib 一 简介: 二 相关文档: 三 入门与进阶案例 1- 简单图形绘制 2- figure的简单使用 3- 设置坐标轴 4- 设置legend图例 5- 添加注解和绘制点以及在图形上 ...

  4. matplotlib python高级绘图库 一周总结

    matplotlib python高级绘图库 一周总结 官网 http://matplotlib.org/ 是一个python科学作图库,可以快速的生成很多非常专业的图表. 只要你掌握要领,画图将变得 ...

  5. Matplotlib学习---用matplotlib画箱线图(boxplot)

    箱线图通过数据的四分位数来展示数据的分布情况.例如:数据的中心位置,数据间的离散程度,是否有异常值等. 把数据从小到大进行排列并等分成四份,第一分位数(Q1),第二分位数(Q2)和第三分位数(Q3)分 ...

  6. Python 绘图库Matplotlib入门教程

    0 简单介绍 Matplotlib是一个Python语言的2D绘图库,它支持各种平台,并且功能强大,能够轻易绘制出各种专业的图像. 1 安装 pip install matplotlib 2 入门代码 ...

  7. python画图库及函数,绘制图片从文件提取出来的数据集转化为int,不然作为坐标轴的时候因为是字符串而无法排序

    转化int:  

  8. Matplotlib学习---用matplotlib画直方图/密度图(histogram, density plot)

    直方图用于展示数据的分布情况,x轴是一个连续变量,y轴是该变量的频次. 下面利用Nathan Yau所著的<鲜活的数据:数据可视化指南>一书中的数据,学习画图. 数据地址:http://d ...

  9. Python的可视化包 – Matplotlib 2D图表(点图和线图,.柱状或饼状类型的图),3D图表(曲面图,散点图和柱状图)

    Python的可视化包 – Matplotlib Matplotlib是Python中最常用的可视化工具之一,可以非常方便地创建海量类型地2D图表和一些基本的3D图表.Matplotlib最早是为了可 ...

随机推荐

  1. BZOJ 2302: [HAOI2011]Problem c( dp )

    dp(i, j)表示从i~N中为j个人选定的方案数, 状态转移就考虑选多少人为i编号, 然后从i+1的方案数算过来就可以了. 时间复杂度O(TN^2) ------------------------ ...

  2. DSP的cache一般在何时会生效,防止在cache使用造成数据不一致

    在使用DSP的cache使能所有的ddr操作时,发现如果只是写操作,根据cache的机制,如果没有在了L1级hit,则直接使用write buffer来完成写操作. 假如hit的话,那之前一定发生过读 ...

  3. h5的api dom全屏展示

    下面是完整的例子,暂不做分析 <!DOCTYPE html> <html> <head> <title> FullScreen API 演示</t ...

  4. Windows 桌面边栏小工具开发入门

          准备为网站做一个桌面通知功能的工具,现在网上一般是html5+js的比较多.虽然html5+js现在是web的开发主流,但是我们应用一般是windows系统.并且应使用中,需要打开谷歌或其 ...

  5. ubantu root 默认密码

    安装完Ubuntu后忽然意识到没有设置root密码,不知道密码自然就无法进入根用户下.到网上搜了一下,原来是这麽回事.Ubuntu的默认root密码是随机的,即每次开机都有一个新的root密码.我们可 ...

  6. //Build/ 2014 开发者大会Azure重点整理

     寓教于乐,轻松掌握 Windows Apps和 Cloud //Build/ 2014开发者大会第二天重点整理 (上) //Build/ 2014开发者大会第二天的主题演讲主要包含两部分:Mic ...

  7. CentOS 6.4 U盘启动盘制作、安装及遇到的问题解决

    用UltraISO Premium Edition  9.3 制作的CentOS 6.4 U盘安装盘, 制作过程參考我写的百度经验:UltraISO制作U盘系统盘安装CentOS经验分享 安装时提示P ...

  8. ssh环境搭建并实现登录功能

    参照了这篇博客,但是里面有些地方进行了更改 http://wenku.baidu.com/link?url=edeegTquV2eR3CJ5-zvNcJbyuq11Afp-lD2Fz2jfmuHhV1 ...

  9. VS2015+MySql EF的配置问题

    自己做笔记,防止以后各种找! 去MySql下载最新版的安装包,MySql For Windows全部就可以了,根据开发需求安装功能,然后安装MySql的步骤上网去找一大堆. 注意事项: 第一:必须把V ...

  10. C# 微信公众平台开发(2)-- 微信菜单

    上一篇了解微信开发者中心 URL的配置验证: 验证成功后,就可以对获取的接口权限进行操作 自定义菜单接口可实现多种类型按钮,用的比较多的是 1.click:点击推事件 用户点击click类型按钮后,微 ...