文章目录
- matplotlib
* - 点线
- 散点
- 样式
- 坐标系
- 数学之心
- 等高线
- 热力图
- 饼图
- 分图显示
- scatter 3D
- wireframe 3D
- surface 3D
- contour 3D
- 经济柱形图
- 人口柱形图
- 股票图
- turtle
* - bdd
- shock
- shock2
- 随机字
- tree
- networkx
* - BA网络
- 社交网络
- 最短路径
- mayavi
* - barchart
- colormap
- contour3d
- plot3d
- opengl
最后更新
2022.02.12
绘图库大全:
matplotlib底层灵活可实现复杂操作
seaborn是mp的上层更简单
pyecharts百度的图表可视化库
basemap地理地图
pygal矢量图
networkx网络
plotly地图趋势
turtle作画
mayavi三维可视化
opengl开放图形库
其他的还有pyqtgraph、pyQT5、PIL(pillow)、tkinter、holoviews、altair、vispy、bokeh等
matplotlib
一般用import matplotlib.pyplot as plt;import numpy as np
而pylab是把上两个都包含了,快速开发简单的可以用,复杂的还是不用pylab,调用耗时
matplotlib.patches包是形状,但不常用
点线
import matplotlib.pyplot as plt
import numpy as np
plt.plot( [1,2],[1,2],'--b',[1,2],[1,3], '--b', label='curve_fit values', linewidth=1)
plt.plot( [1,2],[1,2], '*r',[1,2],[1,3], '*r', label='original values',markersize=30
, markeredgewidth=1, markeredgecolor="grey")
plt.plot([1,3],[2,2],'ob:')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x=np.array([[0,1,2],[3,4,5],[6,7,8]])
y=np.array([[2,3,2],[3,4,3],[4,5,4]])
plt.plot(x,y)
plt.legend(['a','b','c'],loc=4)
plt.show()
散点
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(-100,100,0.1)
plt.title('x')
plt.plot(x,x*np.cos(x),'c')
plt.plot(x,x*np.sin(x),'g')
plt.show()
exit()
n = 10
x = np.random.rand(n)
y = np.random.rand(n)
plt.scatter(x,y,200,'r','*',alpha=0.6,linewidths=1,edgecolors='g')
plt.show()
n = 50
x = np.random.rand(n)
y = np.random.rand(n)
q = np.random.rand(n)
w = np.random.rand(n)
from matplotlib import colors
changecolor = colors.Normalize(vmin=0.4, vmax=0.8)
plt.scatter(x,y,q*600,w,'o',alpha=0.5, cmap='viridis',norm=changecolor)
plt.colorbar()
plt.show()
样式
plt.style.use('seaborn')
plt.figure(figsize=(10,5))
subplot(1,1,1)
x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x,y1,color='b',linewidth=2.0,linestyle="-",label = "sinx")
plt.plot(x,y2,color='r',linewidth=2.0,linestyle="-",label = "cosx")
plt.text(-2,0.5,'y=x*x')
plt.text(2,-1,r'$ y=\cos(\frac{\pi}{2}) $')
plt.xlabel('x')
plt.ylabel('y')
plt.fill(x,y1,'c')
plt.legend(loc='best')
plt.show()
plt.style.use('bmh')
x=np.arange(-100,100,0.1)
y1=x*np.cos(x/5)
y2=x*np.sin(x/5)
plt.plot(x,y1,'c')
plt.plot(x,y2,'g')
plt.fill_between(x,y1,y2)
plt.show()
坐标系
from pylab import *
figure(figsize=(8,6))
x = linspace(-np.pi, np.pi, 250,endpoint=True)
plot(x, cos(x), color="b", linewidth=2, linestyle="-")
ax = gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
yticks([-1,-0.5, 0,0.5, 1])
show()
数学之心
from pylab import *
style.use('seaborn')
x = linspace(-2, 2, 140,endpoint=True)
z=abs(x)**(2/3)+0.8*sqrt(3.3-x**2)*sin(1100*pi*x)
plot(x, z, color="r", linewidth=2, linestyle="-")
show()
等高线
from pylab import *
n = 1000
x, y = meshgrid(np.linspace(-3, 3, n),linspace(-3, 3, n))
print(x.shape,y.shape)
y1 = np.random.uniform(0.5, 1.0, n)
y2 = np.random.uniform(0.5, 1.0, n)
z = (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
cntr = contour(x, y, z, 8, colors='black', linewidths=0.5)
clabel(cntr, inline_spacing=1, fmt='%.1f', fontsize=10)
cntr = contourf(x, y, z, 8, cmap='jet')
show()
热力图
from pylab import *
subplot(121)
X,Y = np.meshgrid(np.linspace(-3,3,4),np.linspace(-3,3,4))
imshow(X*Y*cos(X), cmap='jet')
subplot(122)
x,y = np.meshgrid(np.linspace(-3,3,400),np.linspace(-3,3,400))
imshow(x*y*cos(x)+x**2+y/0.1, cmap='jet')
show()
饼图
from pylab import *
pie([17, 100, 31, 21, 26],
[0.01, 0.01, 0.11, 0.01, 0.01],
['PHP', 'Python', 'Go', 'C++', 'Java'],
['blue', 'yellow', 'red', 'green','c'],
'%d%%',shadow=True,startangle=90)
show()
分图显示
from pylab import *
subplot(2,1,1)
contourf(array([[33,11],[33,-3]]))
subplot(2,2,3)
pie([23,55,11])
subplot(2,4,7)
imshow([[3,4],[3,4]])
subplot(2,4,8)
plot([2,3],[4,5],'r')
twinx()
show()
scatter 3D
from pylab import *
from mpl_toolkits.mplot3d import axes3d
n = 1000
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
z = np.random.normal(0, 1, n)
d = np.sqrt(x ** 2 + y ** 2 + z ** 2)
ax =gca(projection='3d')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.scatter(x, y, z, s=60, c=d, cmap="jet_r", alpha=0.6, marker='*')
show()
wireframe 3D
from pylab import *
from mpl_toolkits.mplot3d import axes3d
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 3, n))
y1 = np.random.uniform(0.5, 1.0, n)
y2 = np.random.uniform(0.5, 1.0, n)
z =(x**2 - y**3+abs(sin(y))*10)
ax =gca(projection='3d')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.plot_wireframe(x, y, z, rstride=30, cstride=30, linewidth=0.5, color='c')
show()
surface 3D
from pylab import *
from mpl_toolkits.mplot3d import axes3d
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n), np.linspace(-3, 3, n))
y1 = np.random.uniform(0.5, 1.0, n)
y2 = np.random.uniform(0.5, 1.0, n)
z = (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
ax =gca(projection='3d')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.plot_surface(x, y, z, rstride=10, cstride=10, cmap='jet')
show()
contour 3D
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.01)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.5, cmap='jet')
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
plt.show()
经济柱形图
b=pd.read_excel('jj.xls')
bb=np.array(b)
print(bb.shape)
print(bb[5:-3])
from pylab import *
title('各行业企业经济情况',fontsize=20)
rcParams['font.sans-serif'] = ['FangSong']
lb=bb[6:-3][:,0]
lens=len(lb)
bar(range(0,lens*2,2),bb[6:-3][:,1],label=lb,color='violet',width=0.6,alpha=1)
for a, b in zip(range(0,lens*2,2),bb[6:-3][:,1]):
plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=10)
xticks([i for i in range(0,lens*2,2)],lb,rotation=270)
ylabel('企业个数')
twinx()
ylabel('企业资产(亿)')
bar([i+0.5 for i in range(0,lens*2,2)],bb[6:-3][:,2],color='b',width=0.6,alpha=1)
for a,c in zip(range(0,lens*2,2),bb[6:-3][:,2]):
plt.text(a+0.5, c + 0.05, '%.0f' % c, ha='center', va='bottom', fontsize=10)
show()
人口柱形图
a=pd.read_excel('man.xls')
print(a)
aa=np.array(a)
print(aa.shape)
print(aa[6:])
aasum=aa[6]
aa=aa[7:,:8]
from pylab import *
style.use('seaborn')
title('人口普查')
rcParams['font.sans-serif'] = ['FangSong']
rcParams['axes.unicode_minus'] = False
lb=aa[:,0]
lens=aa.shape[0]
barh(lb,aa[:,5]/aasum[5]*100,label='男',color='m')
barh(lb,-aa[:,6]/aasum[6]*100,label='女',color='deepskyblue')
for a, b,c in zip(range(lens),-aa[:,6]/aasum[6]*100,aa[:,5]/aasum[5]*100):
plt.text(b-0.2 ,a, round(b,1), ha='center', va='center', fontsize=10)
plt.text(c+0.2 ,a, round(c,1), ha='center', va='center', fontsize=10)
xlim(-10,10)
xlabel('人数占比')
ylabel('各省份')
legend(loc="upper",ncol=2,frameon=False)
show()
股票图
c=pd.read_csv('df.csv',encoding='gbk')
cc=np.array(c)
print(cc.shape)
d5,d10,d20,d30,d60=[],[],[],[],[]
sp=cc[:,4]
rule = re.compile(r",")
hp=[int(rule.sub('', i)) for i in cc[:,7]]
M5,M10=[],[]
for i in range(150):
d5.append(sum(sp[-150-5+i:-150+i])/5)
d10.append(sum(sp[-150-10+i:-150+i])/10)
d20.append(sum(sp[-150-20+i:-150+i])/20)
d30.append(sum(sp[-150-30+i:-150+i])/30)
d60.append(sum(sp[-150-60+i:-150+i])/60)
M5.append(sum(hp[-150-5+i:-150+i])/5)
M10.append(sum(hp[-150-10+i:-150+i])/10)
cc=cc[-150:]
from pylab import *
rcParams['font.sans-serif'] = ['FangSong']
subplot(2,1,1)
title('东方电缆(SH:603606)')
n=0
low,up=0,0
usec=[]
for i in cc:
n+=1
k,g,d,s=i[1:5]
if k<s:color='r'
if k>s:color='green'
if k==s:color='gray'
usec.append(color)
plot([n,n],[k,s],color,linewidth=5)
plot([n,n],[min(k,s),d],color,linewidth=1)
plot([n,n],[max(k,s),g],color,linewidth=1)
low,up=min(low,d),max(up,g)
yticks(linspace(low,up,5,endpoint=True))
grid(linestyle='--',axis='y')
xlim(0,n)
plot(range(150),d5,'-y',label='MA5')
plot(range(150),d10,'-b',label='MA10')
plot(range(150),d20,'-m',label='MA20')
plot(range(150),d30,'-c',label='MA30')
plot(range(150),d60,'-g',label='MA60')
legend()
xticks([])
subplot(4,1,3)
hand=cc[:,7]
print(hand[4],type(hand[4]))
rule = re.compile(r",")
hand=[int(rule.sub('', i)) for i in hand]
hup=max( hand)
yticks(linspace(1,hup,5,endpoint=True))
for i in range(150):
bar(i,int(hand[i]),color=usec[i])
xlim(0,n)
plot(range(150),M5,'-y',label='M5')
plot(range(150),M10,'-b',label='M10')
legend(ncol=2)
show()
exit()
turtle
它是是py自带包,海龟作图
bdd
图
import turtle
turtle.title('zzz')
turtle.speed(5000)
turtle.penup()
turtle.goto(177, 112)
turtle.pencolor("lightgray")
turtle.pensize(3)
turtle.fillcolor("white")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(80)
turtle.circle(-45, 200)
turtle.circle(-300, 23)
turtle.end_fill()
turtle.penup()
turtle.goto(182, 95)
turtle.pencolor("black")
turtle.pensize(1)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.setheading(95)
turtle.pendown()
turtle.circle(-37, 160)
turtle.circle(-20, 50)
turtle.circle(-200, 30)
turtle.end_fill()
turtle.penup()
turtle.goto(-73, 230)
turtle.pencolor("lightgray")
turtle.pensize(3)
turtle.fillcolor("white")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(20)
turtle.circle(-250, 35)
turtle.setheading(50)
turtle.circle(-42, 180)
turtle.setheading(-50)
turtle.circle(-190, 30)
turtle.circle(-320, 45)
turtle.circle(120, 30)
turtle.circle(200, 12)
turtle.circle(-18, 85)
turtle.circle(-180, 23)
turtle.circle(-20, 110)
turtle.circle(15, 115)
turtle.circle(100, 12)
turtle.circle(15, 120)
turtle.circle(-15, 110)
turtle.circle(-150, 30)
turtle.circle(-15, 70)
turtle.circle(-150, 10)
turtle.circle(200, 35)
turtle.circle(-150, 20)
turtle.setheading(-120)
turtle.circle(50, 30)
turtle.circle(-35, 200)
turtle.circle(-300, 23)
turtle.setheading(86)
turtle.circle(-300, 26)
turtle.setheading(122)
turtle.circle(-53, 160)
turtle.end_fill()
turtle.penup()
turtle.goto(-137, 170)
turtle.pencolor("black")
turtle.pensize(1)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(120)
turtle.circle(-37, 160)
turtle.setheading(210)
turtle.circle(160, 20)
turtle.end_fill()
turtle.penup()
turtle.goto(90, 230)
turtle.setheading(40)
turtle.begin_fill()
turtle.pendown()
turtle.circle(-30, 170)
turtle.setheading(125)
turtle.circle(150, 23)
turtle.end_fill()
turtle.penup()
turtle.goto(-180, -55)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.setheading(-120)
turtle.pendown()
turtle.circle(50, 30)
turtle.circle(-27, 200)
turtle.circle(-300, 20)
turtle.setheading(-90)
turtle.circle(300, 14)
turtle.end_fill()
turtle.penup()
turtle.goto(110, -173)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(-115)
turtle.circle(110, 15)
turtle.circle(200, 10)
turtle.circle(-18, 80)
turtle.circle(-180, 13)
turtle.circle(-20, 90)
turtle.circle(15, 60)
turtle.setheading(42)
turtle.circle(-200, 29)
turtle.end_fill()
turtle.penup()
turtle.goto(-40, -215)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(-155)
turtle.circle(15, 100)
turtle.circle(-10, 110)
turtle.circle(-100, 30)
turtle.circle(-15, 65)
turtle.circle(-100, 10)
turtle.circle(200, 15)
turtle.setheading(-14)
turtle.circle(-200, 27)
turtle.end_fill()
turtle.penup()
turtle.goto(-64, 120)
turtle.begin_fill()
turtle.pendown()
turtle.setheading(40)
turtle.circle(-35, 152)
turtle.circle(-100, 50)
turtle.circle(-35, 130)
turtle.circle(-100, 50)
turtle.end_fill()
turtle.penup()
turtle.goto(-47, 55)
turtle.fillcolor("white")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(0)
turtle.circle(25, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(-45, 62)
turtle.pencolor("darkslategray")
turtle.fillcolor("darkslategray")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(0)
turtle.circle(19, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(-45, 68)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(0)
turtle.circle(10, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(-47, 86)
turtle.pencolor("white")
turtle.fillcolor("white")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(0)
turtle.circle(5, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(51, 82)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(120)
turtle.circle(-32, 152)
turtle.circle(-100, 55)
turtle.circle(-25, 120)
turtle.circle(-120, 45)
turtle.end_fill()
turtle.penup()
turtle.goto(79, 60)
turtle.fillcolor("white")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(0)
turtle.circle(24, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(79, 64)
turtle.pencolor("darkslategray")
turtle.fillcolor("darkslategray")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(0)
turtle.circle(19, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(79, 70)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(0)
turtle.circle(10, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(79, 88)
turtle.pencolor("white")
turtle.fillcolor("white")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(0)
turtle.circle(5, 360)
turtle.end_fill()
turtle.penup()
turtle.goto(37, 80)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.pendown()
turtle.circle(-8, 130)
turtle.circle(-22, 100)
turtle.circle(-8, 130)
turtle.end_fill()
turtle.penup()
turtle.goto(-15, 48)
turtle.setheading(-36)
turtle.begin_fill()
turtle.pendown()
turtle.circle(60, 70)
turtle.setheading(-132)
turtle.circle(-45, 100)
turtle.end_fill()
turtle.penup()
turtle.goto(-135, 120)
turtle.pensize(5)
turtle.pencolor("cyan")
turtle.pendown()
turtle.setheading(60)
turtle.circle(-164, 150)
turtle.circle(-130, 78)
turtle.circle(-252, 30)
turtle.circle(-136, 105)
turtle.penup()
turtle.goto(-131, 116)
turtle.pencolor("slateblue")
turtle.pendown()
turtle.setheading(60)
turtle.circle(-160, 144)
turtle.circle(-122, 78)
turtle.circle(-239, 30)
turtle.circle(-135, 106)
turtle.penup()
turtle.goto(-127, 112)
turtle.pencolor("orangered")
turtle.pendown()
turtle.setheading(60)
turtle.circle(-155, 136)
turtle.circle(-116, 86)
turtle.circle(-220, 30)
turtle.circle(-134, 103)
turtle.penup()
turtle.goto(-123, 108)
turtle.pencolor("gold")
turtle.pendown()
turtle.setheading(60)
turtle.circle(-150, 136)
turtle.circle(-104, 86)
turtle.circle(-220, 30)
turtle.circle(-126, 102)
turtle.penup()
turtle.goto(-120, 104)
turtle.pencolor("greenyellow")
turtle.pendown()
turtle.setheading(60)
turtle.circle(-145, 136)
turtle.circle(-90, 83)
turtle.circle(-220, 30)
turtle.circle(-120, 100)
turtle.penup()
turtle.penup()
turtle.goto(225, 110)
turtle.pencolor("brown")
turtle.pensize(1)
turtle.fillcolor("brown")
turtle.begin_fill()
turtle.pendown()
turtle.setheading(36)
turtle.circle(-8, 180)
turtle.circle(-60, 24)
turtle.setheading(110)
turtle.circle(-60, 24)
turtle.circle(-8, 180)
turtle.end_fill()
turtle.pensize(2)
turtle.penup()
turtle.goto(-15, -160)
turtle.pendown()
turtle.pencolor("blue")
turtle.circle(6)
turtle.penup()
turtle.goto(0, -160)
turtle.pendown()
turtle.pencolor("black")
turtle.circle(6)
turtle.penup()
turtle.goto(15, -160)
turtle.pendown()
turtle.pencolor("brown")
turtle.circle(6)
turtle.penup()
turtle.goto(-8, -165)
turtle.pendown()
turtle.pencolor("lightgoldenrod")
turtle.circle(6)
turtle.penup()
turtle.goto(6, -165)
turtle.pendown()
turtle.pencolor("green")
turtle.circle(6)
turtle.penup()
turtle.pencolor("black")
turtle.goto(-30, -148)
turtle.write("BEIJING 2022", font=('Arial', 10, 'bold italic'))
turtle.hideturtle()
turtle.goto(-30, -348)
turtle.write("对齐了没", font=('Arial', 20))
turtle.hideturtle()
turtle.done()
shock
import turtle as t
angle = 60
t.setup(1280,720)
t.bgcolor('black')
t.pensize(1)
randomColor = ['red','blue','green','purple','gold','pink']
t.speed(1000)
for i in range(1000):
t.color(randomColor[i%6])
t.fd(i)
t.rt(angle+0.5)
t.up()
t.color("#0fe6ca")
t.goto(-1000,-1000)
t.down()
t.done()
shock2
from turtle import *
speed(1000)
colormode(255)
clrs = ["MidnightBlue", "Navy", "DarkBlue", "MediumBlue", "RoyalBlue", "MediumSlateBlue", "CornflowerBlue",
"DodgerBlue", "DeepskyBlue", "LightSkyBlue", "SkyBlue", "LightBlue"]
for j in range(120):
cn = 0
c = 30
f = 70
for i in range(12):
pencolor(clrs[cn])
circle(c)
left(90)
penup()
forward(f)
right(90)
pendown()
c = c * 0.8
f = f * 0.8
circle(c)
cn = cn + 1
penup()
goto(0, 0)
forward(5)
right(3)
pendown()
done()
随机字
from turtle import *
import random
strs= """
时光不老 我们不散。
心若向阳 无畏悲伤。
你若安好 便是晴天。
心有灵犀 一点就通。
人来人往 繁华似锦。
生能尽欢 死亦无憾。
花开花落 人世无常。
""".split("。")
setup(1280,720)
colormode(255)
up()
a, b = -500, 280
goto(a,b)
bgcolor("black")
down()
def w(strs,b):
bgcolor( 70,0,140)
for i in range(len(strs)):
up()
goto(a+100*i,b)
down()
size = random.randint(12,68)
color( random.randint(60,255),random.randint(0,255),random.randint(60,255))
write(strs[i], align="center",font=("楷体",size))
for i in range(7):
w(strs[i],b-100*i)
up()
color("#262626;")
goto(-1000,-1000)
down()
ht()
done()
tree
from turtle import *
from random import *
from math import *
def tree(n, l):
pd()
t = cos(radians(heading() + 45)) / 8 + 0.25
pencolor(t, t, t)
pensize(n / 4)
forward(l)
if n > 0:
b = random() * 15 + 10
c = random() * 15 + 10
d = l * (random() * 0.35 + 0.6)
right(b)
tree(n - 1, d)
left(b + c)
tree(n - 1, d)
right(c)
else:
right(90)
n = cos(radians(heading() - 45)) / 4 + 0.5
pencolor(n, n, n)
circle(2)
left(90)
pu()
backward(l)
bgcolor(0.5, 0.5, 0.5)
ht()
speed(0)
tracer(0, 0)
left(90)
pu()
backward(300)
tree(13, 100)
done()
networkx
networkx是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行复杂网络数据分析、仿真建模等工作。
利用networkx可以以标准化和非标准化的数据格式存储网络、生成多种随机网络和经典网络、分析网络结构、建立网络模型、设计新的网络算法、进行网络绘制等。
networkx支持创建简单无向图、有向图和多重图(multigraph);内置许多标准的图论算法,节点可为任意数据;支持任意的边值维度,功能丰富,简单易用。
networkx以图(graph)为基本数据结构。图既可以由程序生成,也可以来自在线数据源,还可以从文件与数据库中读取。
基本流程:
1. 导入networkx,matplotlib包
2. 建立网络
3. 绘制网络 nx.draw()
4. 建立布局 pos = nx.spring_layout美化作用
BA网络
import random
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node('a')
G.add_node('d')
G.add_nodes_from(['b', 'c'])
G.add_edge('a','db')
print(G.number_of_nodes())
print(G.number_of_edges())
G.add_nodes_from([3, 4, 5, 6, 8, 9, 10, 11, 12])
G.add_edges_from([(3, 5), (3, 6), (6, 7)])
nx.draw(G,node_color='r')
plt.show()
G =nx.random_graphs.barabasi_albert_graph(100,1)
nx.draw(G,node_color=[random.random() for i in range(100)],edge_color = 'c',font_size =18,node_size=50)
plt.show()
社交网络
import random
import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.bipartite as bipartite
G = nx.davis_southern_women_graph()
women = G.graph['top']
clubs = G.graph['bottom']
W = bipartite.projected_graph(G, women)
W = bipartite.weighted_projected_graph(G, women)
nx.draw(G, node_color="m",edge_color =[random.random() for i in range(G.number_of_edges())],font_size =10,node_size=40, with_labels=True)
plt.show()
最短路径
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_weighted_edges_from([('0', '3', 3), ('0', '1', -5), ('0', '2', 2), ('1', '2', 4), ('2', '3', 1)])
edge_labels = nx.get_edge_attributes(G, 'weight')
labels = {'0': '0', '1': '1', '2': '2', '3': '3'}
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_color='g', node_size=500, alpha=0.8)
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5, edge_color='b')
nx.draw_networkx_labels(G, pos, labels, font_size=16)
nx.draw_networkx_edge_labels(G, pos, edge_labels)
paths = nx.johnson(G, weight='weight')
print(paths)
plt.show()
mayavi
三维可视化
安装mayavi时不能pip,手动安装顺序为PyQt4–>Traits–>VTK–>Mayavi,找对应版本的whl
barchart
import random
import mayavi.mlab as mlab
import numpy as np
s = np.random.rand(3,3)
mlab.barchart(s)
mlab.vectorbar()
mlab.show()
r1=[random.randint(-100,100) for i in range(1000)]
r2=[random.randint(-100,100) for i in range(1000)]
r3=[random.randint(-100,100) for i in range(1000)]
mlab.barchart(r1,r2,r3)
mlab.vectorbar()
mlab.show()
colormap
s = np.random.rand(3,3)
mlab.imshow(s)
mlab.colorbar()
mlab.show()
contour3d
s = np.random.rand(3,3,3)
mlab.contour3d(s, contours=60, transparent=True)
mlab.colorbar()
mlab.show()
x,y,z=np.mgrid[-5.:5:64j,-5.:5:64j,-5.:5:64j]
scalars=x**4+y**4+z**4
obj=mlab.contour3d(scalars,contours=8,transparent=True)
mlab.colorbar()
mlab.show()
plot3d
def peaks(x,y):
return 3.0*(1.0-x)**2*np.exp(-(x**2) - (y+1.0)**2) - 10*(x/5.0 - x**3 - y**5) * np.exp(-x**2-y**2) - 1.0/3.0*np.exp(-(x+1.0)**2 - y**2)
y,x = np.mgrid[-5:5:700j,-5:5:700j]
z=peaks(x,y)
mlab.mesh(x,y,z)
mlab.colorbar()
mlab.show()
x, y = np.mgrid[-10:10:100j, -10:10:100j]
r = np.sqrt(x**2 + y**2)
z = np.sin(r)*r*2
mlab.surf(z, warp_scale='auto')
mlab.colorbar()
mlab.show()
t=mgrid[-pi:pi:50j]
s=sin(t)
mlab.points3d(cos(t),sin(333*t),cos(5*t),s,mode='sphere',line_width=1)
mlab.colorbar()
mlab.show()
n_mer, n_long = 26, 51
dphi = np.pi / 100000.0
phi = np.arange(0.0, 2 * np.pi + 0.5 * dphi, dphi)
mu = phi * n_mer
x = np.cos(mu) * (3 + np.cos(n_long * mu / n_mer) * 0.5)
y = np.sin(mu) * (3+ np.cos(n_long * mu / n_mer) * 0.5)
z = np.sin(n_long * mu / n_mer) * 0.5
mlab.plot3d(x, y, z, np.sin(mu), tube_radius=0.025, colormap='Spectral')
mlab.show()
opengl
它和opencv有点相反,cv是从图像到数据,gl是从数据到图像
Original: https://blog.csdn.net/weixin_42394432/article/details/122851271
Author: 星尘逸风
Title: 一些常用的python绘图包
相关阅读
Title: ImportError: cannot import name ‘Literal‘ from ‘typing‘ (D:Anacondaenvstensorflowlibtyping.py)
报错背景:
因为安装tensorflow-gpu版本需要,我把原来的新建的anaconda环境(我的名为tensorflow)中的python3.8降为了3.7。
在导入seaborn包时,出现了以下错误:
ImportError: cannot import name 'Literal' from 'typing' (D:\Anaconda\envs\tensorflow\lib\typing.py)
原因分析:
这是由于 'Literal' 只支持python3.8版本以上的,对于python3.7并不支持。如果不想升级python版(升级真的很麻烦,可能会导致我的tensorflow-gpu版的不能用了),请看以下解决方法:
情况一:
若你只是单纯的想导入 Literal 的话:
先在你的环境中安装typing_extensions(这是针对python3.8版本以下的使用方法),安装代码如下:
pip install typing_extensions
然后使用以下代码句就可以导入了
from typing_extensions import Literal
情况二:
如果你是像我一样,想导入别的包(如seaborn),却遇到这种错误,以下是报错及解决方法:
报错如下:
解决方法:
找到你的对应路径,打开用红框提示的.py文件(打开方式随你,我是用pycharm打开的),找到对应位置,改成如下:
from typing import (
IO,
TYPE_CHECKING,
Any,
AnyStr,
Callable,
Collection,
Dict,
Hashable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Type as type_t,
TypeVar,
Union,
)
from typing_extensions import (
Literal,
TypedDict,
final,
)
如果还报 ImportError: cannot import name 'xxx' from 'typing'
即再回到此.py文件下进行修改,比如 TypedDict, 不能放到上面from typing import去,否则,则会报类似错误。
我修改完_typing.py文件后,再次运行,又报了以下错误(但是好歹不是之前那个错误了)
No module named 'pandas._libs.interval'
这个错误好改,在你的环境中,安装以下:
pip install --force-reinstall pandas
至此,终于解决问题,可以导入 seaborn 啦。
Original: https://blog.csdn.net/yuhaix/article/details/124528628
Author: 小小_喻
Title: ImportError: cannot import name ‘Literal‘ from ‘typing‘ (D:Anacondaenvstensorflowlibtyping.py)