首页 > 其他分享 >matplotlib库

matplotlib库

时间:2022-10-17 09:38:00浏览次数:71  
标签:plot plt 10 matplotlib np import

matplotlib 是 Python 的绘图库,可以用来绘制各种静态,动态,交互式的图表。
Matplotlib 官网

安装: pip install matplotlib -i https://pypi.douban.com/simple

目录

matplotlib画点

import matplotlib.pyplot as plt

x = 2
y = 3
plt.plot(x, y,'o',label='(2,3)')
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc='lower right')
plt.grid(True)
plt.show()

matplotlib画线

直线

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0, 5])
y = np.array([0, 5])
plt.plot(x, y,'g-.',label='y=x')
plt.plot(x, y, 'o') # 端点
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc='lower right')
plt.grid(True)
plt.show()

折线

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 6, 8])
y = np.array([3, 8, 1, 10])
plt.plot(x, y,'g-.')
plt.plot(x, y, 'o') # 端点
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()

正弦、余弦

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,4*np.pi,0.1)   # start,stop,step
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x,y1,'b-',x,y2,'r:')
plt.xlabel("x")
plt.ylabel("y")
plt.legend(labels=['y1=sin(x)','y2=cos(x)'],loc='lower left')
plt.grid(False)
plt.show()

matplotlib绘制多图

import matplotlib.pyplot as plt
import numpy as np

# 散点图
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([1, 4, 9, 16, 7, 11, 23, 18])
sizes = np.array([20,50,10,20,50,10,60,30]) # 设置点的大小
# 设置点的颜色
# colors = np.array(["red","green","black","orange",
#                    "purple","beige","cyan","magenta"])
colors=np.array([0,10,20,40,60,80,90,100])
plt.subplot(2,2,1)
#plt.scatter(x,y,s=sizes,c=colors)
plt.scatter(x,y,s=sizes,c=colors,cmap='viridis') # 颜色条colormap
plt.title("scatter plot")

# 柱状图
x = np.array(["rose", "violet", "lily", "tulips"])
y = np.array([12, 22, 6, 18])
plt.subplot(2, 2, 2)
plt.bar(x,y,color=["purple","red","hotpink","yellow"])
plt.title("histogram")

# 饼图
y = np.array([35, 25, 25, 15]) # 比例
plt.subplot(2, 2, 3)
# explode 值越大,距离中心越远,默认是0
plt.pie(y,labels=['A','B','C','D'],
        colors=["#d0695d", "#5d9ca8", "#65a479", "#a564c9"],
        autopct='%.1f%%',explode=(0.1, 0, 0, 0))
plt.title("pie")

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# projection为画图样式,除'polar'外还有'aitoff', 'hammer', 'lambert'等
ax=plt.subplot(2,2,4, projection='polar')
ax.plot(x,y)
plt.title("polar graph")

plt.suptitle("multigraph")
plt.show()

ModuleNotFoundError: No module named 'matplotlib.pyplot'; 'matplotlib' is not a package

文件命名的问题,不要写成matplotlib.py!!!!


图像保存 savefig

savfig要在show前面

plt.savefig("./test.png")

import matplotlib.pyplot as plt

x = 2
y = 3
plt.plot(x, y,'o',label='(2,3)')
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc='lower right')
plt.grid(True)
plt.savefig("./test.png") # 保存图像,在plt.show前面!!!!不然是空图
plt.show() # 会进行释放资源

xy轴刻度 xticks、yticks

第一个参数必须是数字,如果不是,要进行值替换。

整数


TypeError: slice indices must be integers or None or have an index method

类型错误:切片索引必须是整数或无,或者有一个__index__ 的方法v


x_ticks_label=["11:{}".format(i) for i in x]
y_ticks=range(51) # 0-50
plt.xticks(x[::10],x_ticks_label[::10]) # 间隔10
plt.yticks(y_ticks[::5])                # 间隔5
plt.xticks(np.linspace(0,15,11)) # (0,15)
plt.yticks(np.arange(-1, 2, 1)) # (-1,2) ,间隔为1
import matplotlib.pyplot as plt
import random

x = range(61)
y = [random.uniform(35,37) for i in x] # 35-37之间的随机数
x_ticks_label=["11:{}".format(i) for i in x]
y_ticks=range(51) # 0-50
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("y")
plt.xticks(x[::10],x_ticks_label[::10]) # 间隔10
plt.yticks(y_ticks[::5])                # 间隔5
plt.show()
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,4*np.pi,0.1)
y0 = np.sin(x)
y1 = np.cos(x)
plt.plot(x, y0)
plt.plot(x, y1)
plt.xlabel("x")
plt.ylabel("y")
plt.xticks(np.linspace(0,15,11)) # (0,15)
plt.yticks(np.arange(-1, 2, 1)) # (-1,2) ,间隔为1
plt.grid(True,linestyle='-.',alpha=0.4)
plt.show()
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,4*np.pi,0.1)
y0 = np.sin(x)
y1 = np.cos(x)
plt.plot(x, y0)
plt.plot(x, y1)
plt.xlabel("x")
plt.ylabel("y")
plt.xticks(np.arange(0, 14, 2))
plt.yticks(np.arange(-1, 2, 1)) # (-1,2) ,间隔为1
plt.grid(True,linestyle='-.',alpha=0.4)
plt.show()

添加网格 grid

plt.grid(True,linestyle='--',alpha=0.3) # linestyle 线型;alpha 透明度(value=0~1)

import matplotlib.pyplot as plt
import random

x = range(61)
y = [random.uniform(35,37) for i in x] # 35-37之间的随机数
x_ticks_label=["11:{}".format(i) for i in x]
y_ticks=range(51) # 0-50
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("y")
plt.xticks(x[::10],x_ticks_label[::10]) # 间隔10
plt.yticks(y_ticks[::5])                # 间隔5
plt.grid(True,linestyle='-.',alpha=0.4)
plt.show()

添加描述信息

plt.xlabel("x") # x轴
# plt.xlabel('x', fontdict={'family': 'Times New Roman', 'size': 16})
plt.ylabel("y") # y轴
plt.title("figure",fontsize=20) # 标题

多次画图(一图多线)

多次plot就行

plt.plot(x,y1)
plt.plot(x,y1)
...
import matplotlib.pyplot as plt
import random

x = range(61)
y0 = [random.uniform(35,37) for i in x] # 35-37之间的随机数
y1 = [random.uniform(20,30) for i in x] # 20-30之间的随机数
x_ticks_label=["11:{}".format(i) for i in x]
y_ticks=range(51) # 0-50
plt.plot(x, y0)
plt.plot(x, y1)
plt.xlabel("x")
plt.ylabel("y")
plt.xticks(x[::10],x_ticks_label[::10]) # 间隔10
plt.yticks(y_ticks[::5])                # 间隔5
plt.grid(True,linestyle='-.',alpha=0.4)
plt.show()

添加图例 legend

legend在显示之前,要声明label

plt.plot(x, y0,label="sin(x)")
plt.legend(loc="best")
location stringlocation code
"best" 0
"upper right" 1
"upper left" 2
"lower left" 3
"lower right" 4
"right" 5
"center left" 6
"center right" 7
"lower center" 8
"upper center" 9
"center" 10
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,4*np.pi,0.1)
y0 = np.sin(x)
y1 = np.cos(x)
plt.plot(x, y0,label="sin(x)")
plt.plot(x, y1,label="cos(x)")
plt.xlabel("x")
plt.ylabel("y")
plt.xticks(np.arange(0, 14, 2))
plt.yticks(np.arange(-1, 2, 1)) # (-1,2) ,间隔为1
plt.legend(loc="best")
# plt.legend(loc=0)
plt.grid(True,linestyle='-.',alpha=0.4)
plt.show()

颜色 color

说明 color 十六进制(6位)
红色 'r' #FF0000
绿色 'g' #00FF00
蓝色 'b' #0000FF
黄色 'y' #FFFF00
青色 'c' #00FFFF
洋红 'm' #FF00FF
黑色 'k' #000000
白色 'w' #FFFFFF

标签:plot,plt,10,matplotlib,np,import
From: https://www.cnblogs.com/Siemens/p/16797972.html

相关文章