Python: 使用 matplotlib 绘制图表

   今天看了一下使用python绘制图表的方法,有个强大的类库matplotlib,可以制作出高质量的2D和3D图形,先记录一下,以后慢慢学习。

   matplotlib下载及API手册地址:http://sourceforge.net/projects/matplotlib/files/matplotlib/

   数学库numpy下载及API手册地址:http://www.scipy.org/Download

   几个绘图的例子,来自API手册:

1、最简单的图:

#!/usr/bin/env python  
import matplotlib.pyplot as plt  
  
plt.plot([10, 20, 30])  
plt.xlabel('tiems')  
plt.ylabel('numbers')  
plt.show()  

测试:

2.饼图:

#!/usr/bin/env python  
# -*- coding: utf-8 -*-  
  
from pylab import *  
  
# make a square figure and axes  
figure(1, figsize=(6,6))  
ax = axes([0.1, 0.1, 0.8, 0.8])  
  
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'  
fracs = [15,30,45, 10]  
  
explode=(0, 0.05, 0, 0)  
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)  
title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})  
savefig('D:\\pie.png')  
show()  


测试:

 

3、使用numpy库函数:

#!/usr/bin/env python  
# -*- coding: utf-8 -*-  
  
import numpy as np  
import matplotlib.pyplot as plt  
  
t = np.arange(0.0, 1.01, 0.01)  
s = np.sin(2*2*np.pi*t)  
  
plt.fill(t, s*np.exp(-5*t), 'r')  
plt.grid(True)  
  
#保存为PDF格式,也可保存为PNG等图形格式  
plt.savefig('D:\\test.pdf')  
plt.show()  

测试:

4. 随机颜色的点图

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 绘制10中大小 100种颜色的散点图
# 创建x
np.random.seed(0)  # 执行多次每次获取的随机数都是一样的
x = np.random.rand(20)
print(x)
y = np.random.rand(20)
print(y)
# 生成10中大小
size = np.random.rand(10) * 1000
# 生成100中颜色
color = np.random.rand(20)
print(x)
print(y)
# 绘制散点图
plt.scatter(x, y, s=size, c=color, alpha=0.7)  # s表示点的大小 c表示点的颜色 alpha表示透明度
plt.show()
'''
注意:点的个数和颜色的个数要相同
      点的个数和点大小的个数可以不同,如果点的个数大于大小的个数,则会循环获取大小
'''

 

5. 带标签的图

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 创建x
x = np.linspace(0, 10, 100)
# 使用legend()图例,给plot方法添加参数label
plt.plot(x, x + 0, '--g', label='--g')
plt.plot(x, x + 1, '-.r', label='-.r')
plt.plot(x, x + 2, ':b', label=':b')
plt.plot(x, x + 3, '.k', label='.k')
plt.plot(x, x + 4, ',c', label=',c')
plt.plot(x, x + 5, '*y', label='*y')
# 左上角upper left fancybox边框  framealpha透明度  shadow阴影  borderpad边框宽度
plt.legend(loc='lower right', fancybox=True, framealpha=0.5, shadow=True,borderpad=1)  # 默认的位置在左上角upper left  可以通过loc进行修改
plt.show()

 6. 柱状图绘制

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 创建x,y  表示x年份  y表示年份对应的销量
x = [1980, 1985, 1990, 1995]
x_label = ['1980年', '1985年', '1990年', '1995年']
y = [1000, 3000, 4000, 5000]
# 调用bar函数绘制柱状图
plt.bar(x, y, width=1)  # width修改柱的宽度 width的值是float类型,并且是 倍数的意思, 打印出来的会自动出现一个合适的宽度。
# 修改中文乱码
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
# 修改x坐标的值 自动 将x-label 替换为 value
plt.xticks(x, x_label)
# 给x坐标y坐标添加名称
plt.xlabel('年份')
plt.ylabel('销量')
# 添加标题title
plt.title('根据年份销量对比图')
plt.show()

6.  bar barh 函数

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 生成x y
np.random.seed(0)
x = np.arange(5)
y = np.random.randint(-5, 5, 5)
print(x,y)
# 将画布分为1行2列  在第一个区域画bar
plt.subplot(1, 2, 1)
# 添加颜色
plt.bar(x, y, color='blue')
# 在0位置水平方向添加蓝色的线条
plt.axhline(0, color='black', linewidth=2)

# 在第二个区域画barh
# barh  将y和x进行对换,竖着方向为x轴
plt.subplot(1, 2, 2)
plt.barh(x, y, color='red')
# 在0位置垂直方向添加红色线条
plt.axvline(0, color='black', linewidth=2)

plt.show()

 


# 生成x y
np.random.seed(0)
x = np.arange(5)
y = np.random.randint(-5, 5, 5)
# 添加颜色
v_bar = plt.bar(x, y, color='blue')

# 对y值大于0设置为蓝色  小于0的柱设置为绿色
for bar, height in zip(v_bar, y):
    if height < 0:
        bar.set(color='green')

plt.show()

7. 柱状图综合使用


# 准备数据
# 三部电影的名称
real_names = ['千与千寻', '玩具总动员4', '黑衣人:全球追缉']
# 3天内票房书
real_num1 = [7548, 4013, 1673]
real_num2 = [5453, 1840, 1080]
real_num3 = [4348, 2345, 1890]
x = np.arange(len(real_names))
# 绘制柱状图
width = 0.3
plt.bar(x, real_num1, alpha=0.5, width=width, label=real_names[0])
plt.bar([i + width for i in x], real_num2, alpha=0.5, width=width, label=real_names[1])
plt.bar([i + 2 * width for i in x], real_num3, alpha=0.5, width=width, label=real_names[2])
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
# 设置x坐标的值  第1天   第2天   第3天
x_label = ['第{}天'.format(i + 1) for i in x]
# print(x_label)
plt.xticks([i + width for i in x], x_label)
# 添加ylabel
plt.ylabel('票房书')
# 添加图例
plt.legend()
# 添加标题
plt.title('3天3部电影票房数')
plt.show()

8. 饼状图

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 准备男、女的人数及比例
man = 71351
woman = 68187
man_perc = man / (woman + man)
woman_perc = woman / (woman + man)
# 添加名称
labels = ['男', '女']
# 添加颜色
colors = ['blue', 'red']
# 绘制饼状图  pie
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
# labels 名称 colors:颜色,explode=分裂  autopct显示百分比
paches, texts, autotexts = plt.pie([man_perc, woman_perc], labels=labels, colors=colors, explode=(0, 0.05),autopct='%0.1f%%')

# 设置饼状图中的字体颜色
for text in autotexts:
    text.set_color('white')

# 设置字体大小
for text in texts + autotexts:
    text.set_fontsize(20)
plt.show()

9.绘制直方图

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 使用np.random.normal()指定期望和均值的正太分布
x = np.random.normal(0, 0.8, 1000)
y = np.random.normal(-2, 1, 1000)
z = np.random.normal(3, 2, 1000)
kwargs = dict(bins=100, alpha=0.5)  # alpha是透明度
plt.hist(x, **kwargs)
plt.hist(y, **kwargs)
plt.hist(z, **kwargs)
plt.show()

10. 绘制等高线

# 导入模块
import matplotlib.pyplot as plt
import numpy as np

# 创建x y
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
# 计算x y相交的点 X Y
X, Y = np.meshgrid(x, y)
# 计算Z
Z = np.sqrt(X ** 2 + Y ** 2)
# 绘制等高线图
# plt.contour(X,Y,Z)
plt.contourf(X, Y, Z)
plt.show()

11. 绘制 3D 图

#导入模块
import matplotlib.pyplot as plt
#导入3d包
from mpl_toolkits.mplot3d import Axes3D
#创建X  Y  Z
X=[1,1,2,2]
Y=[3,4,4,3]
Z=[1,100,1,1]
figure=plt.figure()
#创建Axes3D对象
ax=Axes3D(figure)
ax.plot_trisurf(X,Y,Z)
plt.show()

参考手册

 

posted @ 2017-10-19 19:06  sowhat1412  阅读(202)  评论(0编辑  收藏  举报