本文案例代码的编写在Jupyter Notebook上边进行
一、检查matplotlib是否安装好
! pip show matplotlib
二、画一个普通的散点图
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.linspace(0.,10.,N)
y = np.sin(x)**2 + np.cos(x)
plt.figure()
plt.scatter(x,y,s=50,label = 'y = sin(x)**2 + cos(x)',color = 'y',marker = 'x') #s控制每个点的大小
plt.axis("equal")#轴比例相同
plt.xlabel('x')
plt.ylabel('y')
plt.legend()#显示图例
plt.show()
三、marker的样式
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(100)
N = 50
randx = np.random.random(N)*100
randy = np.random.random(N)*100
plt.figure(figsize=(7,6))
plt.scatter(randx,randy,marker = r'$\beta$',s = 150,color = 'darkorange')
plt.axis('equal')
plt.xlabel('randx')
plt.ylabel('randy')
#plt.show()
plt.tight_layout()
四、不同点大小不一样
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(100)
N = 30
randx = np.random.random(N)*100
randy = np.random.random(N)*100
size = np.random.randint(50,200,size=N)
plt.scatter(randx,randy,s = size,color = 'darkorange')#点的大小不一样
plt.xlabel('randx')
plt.ylabel('randy')
plt.tight_layout()
五、添加子刻度
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(100)
N = 30
randx = np.random.random(N)*100
randy = np.random.random(N)*100
size = np.random.randint(50,200,size=N)
plt.scatter(randx,randy,s = size,color = 'darkorange')#点的大小不一样
from matplotlib.ticker import MultipleLocator
ax = plt.gca()
ax.xaxis.set_minor_locator(MultipleLocator(10))
ax.yaxis.set_minor_locator(MultipleLocator(10))#添加子刻度
plt.xlabel('randx')
plt.ylabel('randy')
plt.tight_layout()
六、不同点颜色不一样
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(100)
N= 30
randx = np.random.random(N)*100
randy = np.random.random(N)*100
size = np.random.randint(50,200,size = N)
plt.figure(figsize = (7,5))
plt.scatter(randx,randy,s = size,c = size,alpha = 0.8) #不同的点颜色而不一样
# ax = plt.gca()
# ax.xaxis.set_minor_locator(MultipleLocator(10))
# ax.yaxis.get_minor_locator(MultipleLocator(10))
plt.axis('equal')
plt.xlabel('randx')
plt.ylabel('randy')
plt.colorbar()
plt.show()
七、自己创建颜色
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap,LinearSegmentedColormap
top = cm.get_cmap('Oranges_r',128)
bottom = cm.get_cmap('Blues',128)
newcolors = np.vstack((top(np.linspace(0,1,128)),bottom(np.linspace(0,1,128))))
orange_blue = ListedColormap(newcolors,name = 'OrangeBlue')
np.random.seed(100)
N = 30
randx = np.random.random(N)*100
randy = np.random.random(N)*100
size = np.random.randint(50,200,size=N)
plt.figure(figsize = (7,5))
plt.scatter(randx,randy,s = size,c = size,alpha = 0.8,cmap = orange_blue)
plt.axis('equal')
ax = plt.gca()
ax.xaxis.set_minor_locator(MultipleLocator(10))
ax.yaxis.set_minor_locator(MultipleLocator(10))
plt.xlabel('randx')
plt.ylabel('randy')
plt.colorbar(label = 'circle size')
plt.show()