matplotlib 初使用

时间:2023-03-09 09:51:06
matplotlib 初使用

试玩了一下 matplotlib, 感觉是:很酥狐吖~ 完全不像 ggplot 那样云里雾里,但是后者展现出的图要漂亮优雅许多。

x = linspace(0, 10, 100) //初始化一个 [0, 10] 的向量,一共 100 个。
print(x) // 我们可以打印看下这个变量长啥样:

[ 0. 0.1010101 0.2020202 0.3030303 0.4040404
0.50505051 0.60606061 0.70707071 0.80808081 0.90909091
1.01010101 1.11111111 1.21212121 1.31313131 1.41414141
1.51515152 1.61616162 1.71717172 1.81818182 1.91919192
2.02020202 2.12121212 2.22222222 2.32323232 2.42424242
2.52525253 2.62626263 2.72727273 2.82828283 2.92929293
3.03030303 3.13131313 3.23232323 3.33333333 3.43434343
3.53535354 3.63636364 3.73737374 3.83838384 3.93939394
4.04040404 4.14141414 4.24242424 4.34343434 4.44444444
4.54545455 4.64646465 4.74747475 4.84848485 4.94949495
5.05050505 5.15151515 5.25252525 5.35353535 5.45454545
5.55555556 5.65656566 5.75757576 5.85858586 5.95959596
6.06060606 6.16161616 6.26262626 6.36363636 6.46464646
6.56565657 6.66666667 6.76767677 6.86868687 6.96969697
7.07070707 7.17171717 7.27272727 7.37373737 7.47474747
7.57575758 7.67676768 7.77777778 7.87878788 7.97979798
8.08080808 8.18181818 8.28282828 8.38383838 8.48484848
8.58585859 8.68686869 8.78787879 8.88888889 8.98989899
9.09090909 9.19191919 9.29292929 9.39393939 9.49494949
9.5959596 9.6969697 9.7979798 9.8989899 10. ]

plot(x, sin(x))  // 画第一条曲线
plot(x, 0.5*cos(2*x)) // 画第二条曲线
title("A Matplotlib Plot")
text(1, -0.8, "A Text Label")
ylim(-1.1, 1.1) // 限定 y 轴的取值范围。不限定的画曲线就会顶到边界,很不好看

然后划出来的图就会长这样:

matplotlib 初使用

x1=linspace(1, 10, 40)
plot(x1, sqrt(x1), 'k-') // k 表示黑色, b 表示蓝色,沿用 matlab 中的助记符

这时候就会 print 出 figure(1):

matplotlib 初使用

figure(2)  // 新建一个画布
x2=linspace(1, 10, 100)
plot(x1, sin(x1), 'k--', x2, 0.2*cos(3*x2), 'k:')

matplotlib 初使用

figure(1) // 重新选择 figure(1)
plot(x1, 3*exp(-x1/2), linestyle='None', color='white', marker='o', markersize=7) // 在上面增加一个用记号 'o' 表示的散点图
savefig('graph1.png') // 存为 png 格式的

matplotlib 初使用

clf() // 擦除画布
ps = plot(x, sin(x), x, cos(x))
t1=text(1, -0.5, "hello")
t2=text(3, 0.5, "hello again")

这时候图片长这样:

matplotlib 初使用

t1.set_position([7, -.5])
t2.set(position=[5, 0], text="good bye")

这时候虽然改变了 t1, t2 的位置信息 / text, 但是图片还是跟原来一样,没有改变,必须显示的调用 draw() 函数才可以改变:

draw()

这时候图片就更新成这样了:

matplotlib 初使用

setp([t1,t2], fontsize=10)

但是上面这一句可以立即更新图片,字体变小了:

matplotlib 初使用

t2.remove()  // 擦除一个文字
Artist.remove(ps[1]) // 擦除一条曲线
draw()

擦除完之后:

matplotlib 初使用