canvas教程

Python图表绘制:matplotlib绘图库入门(3)

字号+ 作者:H5之家 来源:H5之家 2016-07-12 11:00 我要评论( )

2.3 直方图 Histograms import numpy as np import pylab as pl# make an array of random numbers with a gaussian distribution with# mean = 5.0# rms = 3.0# number of points = 1000 data = np.random.normal(

2.3 直方图 Histograms

import numpy as np import pylab as pl   # make an array of random numbers with a gaussian distribution with # mean = 5.0 # rms = 3.0 # number of points = 1000 data = np.random.normal(5.0, 3.0, 1000)   # make a histogram of the data array pl.hist(data)   # make plot labels pl.xlabel(’data’) pl.show()

如果不想要黑色轮廓可以改为pl.hist(data, histtype=’stepfilled’)

image

 

2.3.1 自定义直方图bin宽度 Setting the width of the histogram bins manually

增加这两行

bins = np.arange(-5., 16., 1.) #浮点数版本的range
pl.hist(data, bins, histtype=’stepfilled’)

image

 

3 同一画板上绘制多幅子图 Plotting more than one axis per canvas

如果需要同时绘制多幅图表的话,可以是给figure传递一个整数参数指定图标的序号,如果所指定
序号的绘图对象已经存在的话,将不创建新的对象,而只是让它成为当前绘图对象。

fig1 = pl.figure(1)
pl.subplot(211)
subplot(211)把绘图区域等分为2行*1列共两个区域, 然后在区域1(上区域)中创建一个轴对象. pl.subplot(212)在区域2(下区域)创建一个轴对象。

image

You can play around with plotting a variety of layouts. For example, Fig. 11 is created using the following commands:

f1 = pl.figure(1)
pl.subplot(221)
pl.subplot(222)
pl.subplot(212)

image

当绘图对象中有多个轴的时候,可以通过工具栏中的Configure Subplots按钮,交互式地调节轴之间的间距和轴与边框之间的距离。如果希望在程序中调节的话,可以调用subplots_adjust函数,它有left, right, bottom, top, wspace, hspace等几个关键字参数,这些参数的值都是0到1之间的小数,它们是以绘图区域的宽高为1进行正规化之后的坐标或者长度。

pl.subplots_adjust(left=0.08, right=0.95, wspace=0.25, hspace=0.45)

 

4 绘制文件中的数据Plotting data contained in files

4.1 从Ascii文件中读取数据 Reading data from ascii files

读取文件的方法很多,这里只介绍一种简单的方法,更多的可以参考官方文档和NumPy快速处理数据(文件存取)。

numpy的loadtxt方法可以直接读取如下文本数据到numpy二维数组

**********************************************

# fakedata.txt
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81

**********************************************

import numpy as np import pylab as pl   # Use numpy to load the data contained in the file # ’fakedata.txt’ into a 2-D array called data data = np.loadtxt(’fakedata.txt’)   # plot the first column as x, and second column as y pl.plot(data[:,0], data[:,1], ’ro’) pl.xlabel(’x’) pl.ylabel(’y’) pl.xlim(0.0, 10.) pl.show()

image

 

4.2 写入数据到文件 Writing data to a text file

写文件的方法也很多,这里只介绍一种可用的写入文本文件的方法,更多的可以参考官方文档。

import numpy as np # Let’s make 2 arrays (x, y) which we will write to a file # x is an array containing numbers 0 to 10, with intervals of 1 x = np.arange(0.0, 10., 1.) # y is an array containing the values in x, squared y = x*x print ’x = ’, x print ’y = ’, y   # Now open a file to write the data to # ’w’ means open for ’writing’ file = open(’testdata.txt’, ’w’) # loop over each line you want to write to file for i in range(len(x)): # make a string for each line you want to write # ’\t’ means ’tab’ # ’\n’ means ’newline’ # ’str()’ means you are converting the quantity in brackets to a string type txt = str(x[i]) + ’\t’ + str(y[i]) + ’ \n’ # write the txt to the file file.write(txt) # Close your file file.close()

这部分是翻译自:Python Plotting Beginners Guide

对LaTeX数学公式的支持

Matlplotlib对LaTeX有一定的支持,如果记得使用raw字符串语法会很自然:

xlabel(r"$\frac{x^2}{y^4}$")

在matplotlib里面,可以使用LaTex的命令来编辑公式,只需要在字符串前面加一个“r”即可

Here is a simple example:

# plain text
plt.title('alpha > beta')

produces “alpha > beta”.

Whereas this:

     

produces "".

这里给大家看一个简单的例子。

import matplotlib.pyplot as plt

x = arange(1,1000,1)
r = -2
c = 5
y = [5*(a**r) for a in x]

 

fig = plt.figure()

ax = fig.add_subplot(111)
ax.loglog(x,y,label = r"$y = \frac{1}{2\sigma_1^2}, c=5,\sigma_1=-2$")
ax.legend()
ax.set_xlabel(r"x")
ax.set_ylabel(r"y")

程序执行结果如图3所示,这实际上是一个power-law的例子,有兴趣的朋友可以继续google之。

再看一个《用Python做科学计算》中的简单例子,下面的两行程序通过调用plot函数在当前的绘图对象中进行绘图:

plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2)
plt.plot(x,z,"b--",label="$cos(x^2)$")

plot函数的调用方式很灵活,第一句将x,y数组传递给plot之后,用关键字参数指定各种属性:

 

详细的可以参考matplotlib官方教程:

Writing mathematical expressions

Text rendering With LaTeX

有几个问题:

matplotlib使用小结

LaTeX科技排版

参考文献自动搜集管理完美攻略(图文版):Latex+Lyx+Zotero

 

对数坐标轴

在实际中,我们可能经常会用到对数坐标轴,这时可以用下面的三个函数来实现

ax.semilogx(x,y) #x轴为对数坐标轴

ax.semilogy(x,y) #y轴为对数坐标轴

ax.loglog(x,y) #双对数坐标轴

学习资源

Gnuplot的介绍

官方英文资料:

IBM:基于 Python Matplotlib 模块的高质量图形输出(2005年的文章有点旧)

matplotlib技巧集(绘制不连续函数的不连续点;参数曲线上绘制方向箭头;修改缺省刻度数目;Y轴不同区间使用不同颜色填充的曲线区域。)

Python:使用matp绘制不连续函数的不连续点;参数曲线上绘制方向箭头;修改缺省刻度数目;Y轴不同区间使用不同颜色填充的曲线区域。lotlib绘制图表

matplotlib图表中图例大小及字体相关问题

posted on

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 小程序canvas绘制K线,从0开始的日记(一)

    小程序canvas绘制K线,从0开始的日记(一)

    2017-04-30 12:02

  • 利用 HTML5 的 CANVAS 绘制手机应用图表

    利用 HTML5 的 CANVAS 绘制手机应用图表

    2017-04-30 09:00

  • Canvas 绘制时钟

    Canvas 绘制时钟

    2017-04-29 12:04

  • 学习笔记:HTML5 Canvas绘制简单图形

    学习笔记:HTML5 Canvas绘制简单图形

    2017-04-27 13:03

网友点评