python中matplotlib的使用(一)

需要导入matplotlib库

import matplotlib.pyplot as plt

或者

from matplotlib.pyplot import *

1、建立空白图

fig = plt.figure(figsize=(4,2))  
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
plt.show()

subplot()函数中的三个数字,第一个表示y轴方向的子图个数,第二个表示x轴方向子图的个数,第三个则表示当前要画图的焦点。
在这里插入图片描述
这里可以看到图中x,y轴坐标都是从0到1,我们可以使用指定语句来修改坐标起始值:

ax1.axis([-1, 1, -1, 1])

或者

plt.axis([-1, 1, -1, 1])

我们还可以给子图加title以及横纵坐标的label:

ax1.set_title("图的名称")
ax1.set_xlabel(u'x轴名称')
ax1.set_ylabel(u'y轴名称')

2、向图中添加内容

1)、柱状图(bar)

fig = plt.figure(figsize=(4,2))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
x = [0,1,2,3,4,5,6,7,8,9,10]
y1 = [0,1,2,3,4,5,6,7,8,9,10]
y2 = [0,1,2,3,4,5,6,7,8,9,10]
y3 = [0,1,2,3,4,5,6,7,8,9,10]
y4 = [0,1,2,3,4,5,6,7,8,9,10]
ax1.bar(x,y1)
ax1.set_title("figure1")
ax2.bar(x,y2)
ax2.set_title("figure2")
ax3.bar(x,y3)
ax3.set_title("figure3")
ax4.bar(x,y4)
ax4.set_title("figure4")
plt.show()

效果如下:
在这里插入图片描述

2)、扇形图(pie)

y = [2, 3, 8.8, 6.6, 7.0]
plt.figure()
plt.pie(y)
plt.title('PIE')
plt.show()

效果如下:
在这里插入图片描述

3)、散点图(scatter)

x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0,1,2,3,4,5,6,7,8,9,10]
plt.scatter(x, y, color='r', marker='+')
plt.show()

效果如下:
在这里插入图片描述
参数的意义:

  1. x为横坐标轴向量,y为纵坐标轴向量,x,y的长度必须一致。
  2. color控制颜色,常用的颜色如下:
缩写 颜色
b blue
c cyan
g green
k black
m magenta
r rea
w white
y yellow
  1. marker控制标记风格,常用的风格:
符号 风格
. 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
_ Horizontal line (hline symbol) marker
+ Plus marker
x Cross (x) marker

4)、函数图(plot)

from math import *
from numpy import *
x = arange(-math.pi, math.pi, 0.01)
y = [sin(xx) for xx in x]
plt.figure()
plt.title("sinx")
plt.plot(x, y, color='r', linestyle='-.')
plt.show()

效果如下
在这里插入图片描述
参数的意义:
linestyle是控制线形的参数,常用的有:

符号 线形
- 实线
短线
-. 短点相间线
虚点线

5)、二维图形

2D

import numpy as np
delta = 0.025
x = y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = Y**1 + X**2
plt.figure(figsize=(12, 6))
plt.contour(X, Y, Z)
plt.colorbar()
plt.title("2D")
plt.show()

效果如下在这里插入图片描述

读取照片

import matplotlib.image as mpimg
img=mpimg.imread('图片路径')
plt.imshow(img)
plt.title("图片")
plt.show()

ps:若图中中文无法显示的解决办法:
在代码中加入:

plt.rcParams['font.sans-serif']=['SimHei']   # 设置中文字体
plt.rcParams['axes.unicode_minus'] = False   # 设置正负号

参考博客:参考博客
关于matplotlib更详细的内容可以参考官方文档:matplotlib官方文档

代码参考:

https://github.com/ZhangJiangtao-0108/pythonmatplotlib_example.py文件

发布了9 篇原创文章 · 获赞 2 · 访问量 100

猜你喜欢

转载自blog.csdn.net/jocker_775065019/article/details/104819071
今日推荐