(笔记)
#先导如numpy和matplotlib的pyplot
import numpy as np
import matplotlib.pyplot as plt
#linspace参数分别表示从0到10平均分成100块
x = np.linspace(0, 10, 100)
#print (x)
#一个正弦函数
y = np.sin(x)
#print(y)
plt.plot(x, y)
plt.show()
这是我们最终得到的结果图

plt.show这一步是最后渲染生成图的步骤,在此前可以添加其他操作来丰富结果,
比如我们可以在这上面在生成一个余弦函数(改了下变量名,方便记忆)
import numpy as np
import matplotlib.pyplot as plt
#linspace参数分别表示从0到10平均分成100块
x = np.linspace(0, 10, 100)
#print (x)
#一个正弦函数
sinx = np.sin(x)
cosx = np.cos(x)
#print(sinx)
plt.plot(x, sinx)
plt.plot(x,cosx)
plt.show()
得到下图

我们还可以改变线条的默认颜色
在后面添加 color参数 plt.plot(x,cosx,color = 'red')

关于color参数:[https://matplotlib.org/2.0.2/api/colors_api.html]
还可以添加参数linestyle来改变线条的样式
plt.plot(x, cosx, color="red", linestyle="--")

关于linestyle参数:[https://matplotlib.org/devdocs/gallery/lines_bars_and_markers/line_styles_reference.html]
还可以通过plt.axis来控制x,y轴的范围
plt.axis([-1, 12, -2, 2])
四个参数分别表示x起始点,x终止点,y起始点,y终止点

还可以通过添加lable,title标签来为结果图怎加说明
plt.xlabel("x axis")
plt.ylabel("y value")
plt.title('welcome to matplotlib')

我们还可以通过给plt.plot添加label参数来给不同的曲线生成说明
plt.plot(x, sinx,label="sin(x)")
plt.plot(x, cosx, color="red", linestyle="--",label ="cos(x)")

除了上述的折线图,我们还可以用matplotlib生成散点图(Scatter Plot),写法基本一致
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
sinx = np.sin(x)
cosx = np.cos(x)
plt.scatter(x, sinx)
plt.scatter(x, cosx)
plt.show()

还是一样可以添加上述那些参数,和方法来丰富生成的图
一个比较常用的散点图例子--高斯分布
import numpy as np
import matplotlib.pyplot as plt
#三个参数分别表示均值,方差,和生成点的个数
x = np.random.normal(0, 1, 10000)
y = np.random.normal(0, 1, 10000)
plt.scatter(x, y)
plt.show()

我们也可以通过修改透明度来更好的理解高斯分布的特性(越往中间越密集)
plt.scatter(x, y, alpha=0.1)

网友评论