代码1(画神经网络连接图)
from math import cos, sin, atan
import matplotlib.pyplot as plt
# 注意这里并没有用到这个networkx这个库,完全是根据matploblib这个库来画的。
class Neuron():
def __init__(self, x, y,radius,name=None):
self.x = x
self.y = y
self.radius = radius
self.name = name
def draw(self):
circle = plt.Circle((self.x, self.y), radius=self.radius, fill=False)
plt.gca().add_patch(circle)
if(self.name is not None):
plt.text(self.x,self.y,self.name)
#注意这个写法,现在整个图是水平的,不再是竖直的
def plotConnection(neuron1,neuron2):
neuron_radius= neuron1.radius
angle = atan((neuron2.y - neuron1.y)/float(neuron2.x - neuron1.x))
x_adjustment = neuron_radius * cos(angle)
y_adjustment = neuron_radius * sin(angle)
line = plt.Line2D((neuron1.x + x_adjustment, neuron2.x - x_adjustment), (neuron1.y + y_adjustment, neuron2.y - y_adjustment),color="gray")
plt.gca().add_line(line)
class Connection():
def __init__(self,neuron1,neuron2):
self.n1 = neuron1
self.n2 = neuron2
pass
#
radius =0.05
n1 = Neuron(1,1.1,radius,name="n1")
n1.draw()
n2 = Neuron(1,1.3,radius,name="n2")
n2.draw()
n3 = Neuron(1,1.5,radius,name="n3")
n3.draw()
n4 = Neuron(1,1.7,radius)
n4.draw()
n5 = Neuron(1,1.9,radius)
n5.draw()
n6 = Neuron(2,1.0,radius)
n6.draw()
n7 = Neuron(2,1.2,radius,name="n7")
n7.draw()
n8 = Neuron(2,1.4,radius)
n8.draw()
n9 = Neuron(2,1.6,radius,name="n9")
n9.draw()
n10 = Neuron(2,1.8,radius)
n10.draw()
n11 = Neuron(2,2.0,radius)
n11.draw()
plotConnection(n2,n7)
plotConnection(n1,n9)
plotConnection(n3,n8)
plt.axis("scaled")
plt.show()
## 现在这个地方有一个问题,就是这个图形应该是什么样子的
结果如下