① 如何用python画各种着名数学图案
如何用Python画各种着名数学图案 | 附图+代码
用Python绘制着名的数学图片或动画,展示数学中的算法魅力。
Mandelbrot 集
'''
A fast Mandelbrot set wallpaper renderer
reddit discussion:
'''
importnumpy asnp
fromPILimportImage
fromnumba importjit
MAXITERS=200
RADIUS=100
@jit
defcolor(z, i):
v =np.log2(i +1-np.log2(np.log2(abs(z)))) /5
ifv <1.0:
returnv**4, v**2.5, v
else:
v =max(0, 2-v)
returnv, v**1.5, v**3
@jit
defiterate(c):
z =0j
fori inrange(MAXITERS):
ifz.real*z.real +z.imag*z.imag >RADIUS:
returncolor(z, i)
z =z*z +c
return0, 0,0
defmain(xmin, xmax, ymin, ymax, width, height):
x =np.linspace(xmin, xmax, width)
y =np.linspace(ymax, ymin, height)
z =x[None, :] +y[:, None]*1j
red, green, blue =np.asarray(np.frompyfunc(iterate, 1, 3)(z)).astype(np.float)
img =np.dstack((red, green, blue))
Image.fromarray(np.uint8(img*255)).save('mandelbrot.png')
if__name__=='__main__':
main(-2.1, 0.8, -1.16, 1.16, 1200, 960)
② python pyplot 怎么画多变量图
任何画图软件也只能做到3变量,不存在什么多变量的图,3维图可以
fron mpl_toolkits import AXES3
进行导入
③ python pylab怎么输出矢量图
一提到python绘图,matplotlib是不得不提的python最着名的绘图库,它里面包含了类似matlab的一整套绘图的API。因此,作为想要学习python绘图的童鞋们就得在自己的python环境中安装matplotlib库了,安装方式这里就不多讲,方法有很多,给个参考的。
本文将在已安装matplotlib的环境中教新手如何快速使用其中的接口进行绘图操作,并展现一个非常直观的绘图例子,以及控制绘图中的一些细节的方法。
既然绘图要用matplotlib的包,并且我们也已经安装了,那么首先肯定是要引入这个包了: import matplotlib.pyplot as plt
当然也可以替换为引入pylab(是matplotlib的一个子包,非常适合于进行交互式绘图,本文将以这个为例): import pylab as pl
接下来,就是对具体数据进行绘图了。比如我们要绘制一条y=x^2的曲线,可这样写代码:
x = range(10) # 横轴的数据
y = [i*i for i in x] # 纵轴的数据
pl.plot(x, y) # 调用pylab的plot函数绘制曲线
pl.show() # 显示绘制出的图
执行之后就可以看到绘制出来的图了:
可以看到,要显示一个图非常简单,只要有了两个list作为输入数据,先后调用plot和show函数就可以了。一定要记得只有调用了show之后才会显示出来!只有plot是不行的!
在实际运用中,可能这样一条简单粗暴的线可能并不是我们想要的最好的结果,比如,想要在图形上显示原始数据点,很简单,只要在plot函数中加上一个参数即可: pl.plot(x, y, 'ob-') # 显示数据点,并用蓝色(blue)实现绘制该图形
这个参数用法比较灵活,可以从下面的值中组合选择:
颜色(color 简写为 c):
蓝色: 'b' (blue)
绿色: 'g' (green)
红色: 'r' (red)
蓝绿色(墨绿色): 'c' (cyan)
红紫色(洋红): 'm' (magenta)
黄色: 'y' (yellow)
黑色: 'k' (black)
白色: 'w' (white)
线型(linestyle 简写为 ls):
实线: '-'
虚线: '--'
虚点线: '-.'
点线: ':'
点: '.'
点型(标记marker):
像素: ','
圆形: 'o'
上三角: '^'
下三角: 'v'
左三角: '<'
右三角: '>'
方形: 's'
加号: '+'
叉形: 'x'
棱形: 'D'
细棱形: 'd'
三脚架朝下: '1'(像'丫')
三脚架朝上: '2'
三脚架朝左: '3'
三脚架朝右: '4'
六角形: 'h'
旋转六角形: 'H'
五角形: 'p'
垂直线: '|'
水平线: '_'
线是调好了,可是还想加上横纵坐标的说明呢?也很简单,在调用show函数之前添加如下代码:
pl.xlabel(u"我是横轴")
pl.ylabel(u"我是纵轴")
效果如下:
这里一定要记住,传递的字符串一定要是Unicode编码,如果是直接传入字符串,形式如 u'这里是要写的字符串' 即可。
现在就直观多了吧,终于像一个正常的图了,不过,还想再在图里加个图例该咋办?也不难,继续给plot传参数:
pl.plot(x, y, 'ob-', label=u'y=x^2曲线图') # 加上label参数添加图例
pl.legend() # 让图例生效
这里也是一样,label字符串参数务必加上u''声明为unicode编码,否则图例将会添加失败。效果图如下:
oh,看到图像上面光秃秃的,就好想给它加个标题: pl.title(u'图像标题') # 字符串也需要是unicode编码
有时候,我们的数据可能分布并没有这么集中,比如我们想要对项目中的某些数据进行绘图观察时发现,大量数据聚集在0附近,而少量很大的数据会导致图像显示效果很不好,比如:
x = range(10)+[100]
y = [i*i for i in x]
pl.plot(x, y, 'ob-', label=u'y=x^2曲线图')
这时,我们想要限制需要显示的坐标范围:
pl.xlim(-1, 11) # 限定横轴的范围
pl.ylim(-1, 110) # 限定纵轴的范围
再上效果图:
好了,到这里plot的常用绘图用法就讲完了,另外,如果需要在一幅图中显示多条线,可以在show函数调用前继续调用plot函数,传入需要绘制的数据和图形显示要求。
matplotlib是个非常好用的库,不管是对于需要写论文画图,还是数据调研中看数据相关性,都是一个得力助手。写这篇文章的背景是我之前在项目中也使用这个做了一个特征与结果之间的相关性调研中使用到了绘图,就学习了一下,下面是对真实数据进行屏蔽改写之后的一个很像的示意图(感兴趣的可以到我github中看源码,本文的完整代码及注释也可在本链接只中找到):
④ Python的图是矢量图吗
python的图可以转成矢量图。
python将图片转为矢量图的方法步骤
2021-03-30 09:57:10 作者:东方佑
这篇文章主要介绍了python将图片转为矢量图的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
本文主要介绍了python图片转为矢量图,分享给大家,具体如下:
import numpy as np
import matplotlib.pyplot as plt
import cv2
fig, ax = plt.subplots()
plt.figure(1)
image=cv2.imread("2.jpg")
# you can specify the marker size two ways directly:
# 这样一个一个像素太慢了故而要将同样颜色的坐标进行分类处理
color_class=[]
x_y=dict()
for x,w in enumerate(image):
for y,colors in enumerate(w):
if colors.tolist() not in color_class:
s=image[:, :, :1] == colors[0]
s1=image[:, :, 1:2] == colors[1]
s2=image[:, :, 2:3] == colors[2]
ss=s*s1*s2
color_class.append(colors.tolist())
x_y[len(color_class)]=np.where(ss.reshape((ss.shape[0],ss.shape[1])))
print(x,y)
for i ,colors in enumerate(color_class):
a, b = x_y[i + 1]
plt.plot(a,b, ".",color=[colors[2]/255,colors[1]/255,colors[0]/255], markersize=1, label='a') # blue circle with size 20
fig.savefig('scatter.svg', dpi=200, format='svg')
if __name__ == '__main__':
pass
⑤ python 画图,有一个N*N的格子,每一个格子对应着一个数值,根据数值将不同格子绘制不同的颜色,怎么做
fromTkinterimport*
defdrawboard(board,colors,startx=50,starty=50,cellwidth=50):
width=2*startx+len(board)*cellwidth
height=2*starty+len(board)*cellwidth
canvas.config(width=width,height=height)
foriinrange(len(board)):
forjinrange(len(board)):
index=board[i][j]
color=colors[index]
cellx=startx+i*50
celly=starty+j*50
canvas.create_rectangle(cellx,celly,cellx+cellwidth,celly+cellwidth,
fill=color,outline="black")
canvas.update()
root=Tk()
canvas=Canvas(root,bg="white")
canvas.pack()
board=[[1,2,0],[0,2,1],[0,1,2]]
colors=['red','orange','yellow','green','cyan','blue','pink']
drawboard(board,colors)
root.mainloop()
colors必须有不小于最大数值的颜色数
⑥ python可以画出哪些简单图形
一、画一朵花+签名
代码如下:
# -*- coding:utf-8 -*-
#画一朵花+签名
import turtle
turtle.color('red','green')
turtle.pensize(5)
turtle.goto(0,0)
turtle.speed(10)
for i in range(15):
turtle.forward(100)
turtle.right(150)
turtle.up()
turtle.goto(150,-120)
turtle.color('black')
turtle.write("xxx" )
turtle.up()
turtle.goto(160,-140)
turtle.color('black')
turtle.write("2018 年 1 月 10 日" )
turtle.up()
turtle.goto(240,-160)
turtle.color('black')
turtle.write("." )
turtle.done()
二、画五角星脸+签名
代码如下:
# -*- coding:utf-8 -*-
#画五角星脸+签名
import turtle
turtle.color('red','green')
turtle.pensize(5)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.right(144)
turtle.forward(100)
turtle.up()
turtle.goto(150,120)
turtle.down()
turtle.color('red','green')
turtle.forward(50)
turtle.right(144)
turtle.forward(50)
turtle.right(144)
turtle.forward(50)
turtle.right(144)
turtle.forward(50)
turtle.right(144)
turtle.forward(50)
turtle.up()
turtle.goto(-80,90)
turtle.down()
turtle.color('red','green')
turtle.forward(50)
turtle.right(144)
turtle.forward(50)
turtle.right(144)
turtle.forward(50)
turtle.right(144)
turtle.forward(50)
turtle.right(144)
turtle.forward(50)
turtle.up()
turtle.goto(150,-120)
turtle.color('black')
turtle.write("xxx" )
turtle.up()
turtle.goto(160,-140)
turtle.color('black')
turtle.write("2018 年 1 月 7 日" )
turtle.up()
turtle.goto(240,-160)
turtle.color('black')
turtle.write("." )
turtle.done()
⑦ 如何用Python画出下面这种效果的图
mplot3d tutorial
这个?
Quiver
Axes3D.quiver(*args, **kwargs)
Plot a 3D field of arrows.
⑧ python画图如何将数值标到图形上
假设有9张图, 化成3行3列
plt.subplot(331)
plt.plot(...)
plt.subplot(332)
plt.plot(...)
...
plt.subplot(339)
plt.plot(...)
⑨ python的pillow用ImageDraw.Draw.polygon如何填充半透明的颜色
>> fill = (200, 10, 10, 0.5)
对于RGBA模式的图片,填充半透明色,alpha位置取值是0-255,你希望50%,应该是用128,不是0。5
>> 我这里画了一个比如三角形,准备再画一个三角形,也是半透明的,那么这两个颜色是可以混合起来的吧?
直接在同一个Image上绘图是不行的。后面画的会直接覆盖前面的,颜色不会自动融合。如果想要融合的效果,需要用Image.blend(im1, im2, 0.5)或者Image.composite(im1, im2, mask)其中mask需要带alpha参数,可以设置为128.
#!/usr/bin/envpython2
#coding=utf-8
"""
.
"""
fromPILimportImage,ImageDraw
defmain():
im=Image.new("RGBA",(800,800))
draw=ImageDraw.Draw(im)
draw.rectangle((0,0,200,200),fill=(255,0,0,128))
draw.rectangle((400,400,600,600),fill=(255,0,0))
im2=Image.new("RGBA",(800,800))
draw2=ImageDraw.Draw(im2)
draw2.rectangle((100,100,300,300),fill=(0,255,0,128))
draw2.rectangle((500,500,700,700),fill=(0,255,0))
#mergetwoimagesusingblend
blend=Image.blend(im,im2,0.5)
#drawf=ImageDraw.Draw(blend)
#drawf.rectangle((500,100,600,200),fill=(255,0,0))
#drawf.rectangle((600,200,700,300),fill=(0,255,0))
blend.save("/home/sylecn/d/blend.png")
#mergetwoimagesusingcomposite
ones=Image.new("RGBA",(800,800))
_draw=ImageDraw.Draw(ones)
_draw.rectangle((0,0,800,800),fill=(255,255,255,128))
final=Image.composite(im,im2,ones)
final.save("/home/sylecn/d/composite.png")
if__name__=='__main__':
main()
⑩ python matlibplot 怎样画图例
用于添加图例的函数是plt.legend(),我们通过例子来对其进行介绍。
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
#多数据并列柱状图
mpl.rcParams["font.sans-serif"]=["SimHei"]
mpl.rcParams["axes.unicode_minus"]=False
x = np.arange(6)
y1 = [23,5,14,27,18,14]
y2 = [10,27,25,18,23,16]
tick_label = ["A","B","C","D","E","F"]
bar_width = 0.35
plt.bar(x,y1,bar_width,align="center",label="班级A",alpha=0.5)
plt.bar(x+bar_width,y2,bar_width,align="center",label="班级B",alpha=0.5)
plt.xlabel("成绩等级")
plt.ylabel("人数")
plt.xticks(x+bar_width/2,tick_label)
plt.legend(bbox_to_anchor=(1,1),#图例边界框起始位置
loc="upper right",#图例的位置
ncol=1,#列数
mode="None",#当值设置为“expend”时,图例会水平扩展至整个坐标轴区域
borderaxespad=0,#坐标轴和图例边界之间的间距
title="班级",#图例标题
shadow=False,#是否为线框添加阴影
fancybox=True)#线框圆角处理参数
plt.show()
效果如图所示