基础
import matplotlib
.pyplot
as plt
import numpy
as np
x
= np
.linspace
(-10, 10, 100)
y
= x
**2
plt
.plot
(x
, y
)
plt
.show
()
figure
一个plt.figure()后,下面的设置都设置在这个图。可设置线的参数,例如颜色,style等。
import matplotlib
.pyplot
as plt
import numpy
as np
x
= np
.linspace
(-10, 10, 100)
plt
.figure
(num
=1,figsize
=(5,3))
y
= x
**2
plt
.plot
(x
, y
)
plt
.figure
(num
=0,figsize
=(5,3))
y
= np
.sin
(x
)
plt
.plot
(x
, y
,color
="red",linewidth
=2,linestyle
='--')
plt
.show
()
示例代码
import matplotlib
.pyplot
as plt
import numpy
as np
fig
= plt
.figure
()
ax
= fig
.add_subplot
(1,1,1)
ax
.set(xlim
=[0, 20], ylim
=[-1, 4], title
='Math chart',
ylabel
='y', xlabel
='x')
new_ticks
=np
.linspace
(0,20,21)
plt
.xticks
(new_ticks
)
new_ticks
=np
.linspace
(-1,4,6)
plt
.yticks
(new_ticks
)
ax
.xaxis
.set_ticks_position
('bottom')
ax
.spines
['bottom'].set_position
(('data',0))
ax
.yaxis
.set_ticks_position
('left')
ax
.spines
['left'].set_position
(('data',0))
x
= np
.linspace
(0.01,20,1000)
y1
= np
.sin
(x
)
y2
= np
.log
(x
)
y3
= x
**0.2
ax
.plot
(x
, y1
)
ax
.plot
(x
, y2
)
ax
.plot
(x
, y3
)
plt
.show
()
Result
利用plt可视化
plt.parse(0.1)是至少0.1s的意思,如果0.1s内有其它的plt.parse()会延后。否则0.1s后会保留这张图。
plt
.ion
()
for i
in range(100):
plt
.cla
()
plt
.parse
(0.1)
plt
.close
()
plt
.ioff
()
保存
name
='result.png'
plt
.savefig
(name
)
动画
import numpy
as np
import matplotlib
.pyplot
as plt
from matplotlib
import animation
fig
, ax
= plt
.subplots
()
x
= np
.arange
(0, 2*np
.pi
, 0.01)
line
, = ax
.plot
(x
, np
.sin
(x
))
def animate(i
):
line
.set_ydata
(np
.sin
(x
+ i
/10.0))
return line
,
def init():
line
.set_ydata
(np
.sin
(x
))
return line
,
ani
= animation
.FuncAnimation
(fig
=fig
, func
=animate
, frames
=10000, init_func
=init
,
interval
=20, blit
=True)
plt
.show
()
Pycharm动画显示不了:
Setting -> Python Scientific -> show in … 去掉勾