判斷小數點幾位
先將浮點數轉化為字符串,然后截取小數點右邊的字符,在使用len函數。
x=3.25
len(str(x).split(".")[1])
繪制散點圖
#需導入要用到的庫文件
import numpy as np # 數組相關的庫
import matplotlib.pyplot as plt # 繪圖庫
N = 10
x = np.random.rand(N) # 包含10個均勻分布的隨機值的橫坐標數組,大小[0, 1]
y = np.random.rand(N) # 包含10個均勻分布的隨機值的縱坐標數組
plt.scatter(x, y, alpha=0.6) # 繪制散點圖,透明度為0.6(這樣顏色淺一點,比較好看)
plt.show()
調整散點大小
N = 10
x = np.random.rand(N)
y = np.random.rand(N)
area = np.random.rand(N) * 1000 # 包含10個均勻分布的隨機值的面積數組,大小[0, 1000]
fig = plt.figure()
ax = plt.subplot()
ax.scatter(x, y, s=area, alpha=0.5) # 繪制散點圖,面積隨機
plt.show()
調整散點顏色
N = 10
x = np.random.rand(N)
y = np.random.rand(N)
x2 = np.random.rand(N)
y2 = np.random.rand(N)
area = np.random.rand(N) * 1000
fig = plt.figure()
ax = plt.subplot()
ax.scatter(x, y, s=area, alpha=0.5)
ax.scatter(x2, y2, s=area, c=‘green’, alpha=0.6) # 改變顏色
plt.show()
調整散點形狀
N = 10
x = np.random.rand(N)
y = np.random.rand(N)
x2 = np.random.rand(N)
y2 = np.random.rand(N)
x3 = np.random.rand(N)
y3 = np.random.rand(N)
area = np.random.rand(N) * 1000
fig = plt.figure()
ax = plt.subplot()
ax.scatter(x, y, s=area, alpha=0.5)
ax.scatter(x2, y2, s=area, c=‘green’, alpha=0.6)
ax.scatter(x3, y3, s=area, c=area, marker=‘v’, cmap=‘Reds’, alpha=0.7) # 更換標記樣式,另一種顏色的樣式
plt.show()
添加文本(matplotlib.pyplot.text)
語法:matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
import matplotlib.pyplot as plt
plt.style.use(‘seaborn-whitegrid’)
plt.figure(figsize=(5,4),dpi=120)
plt.plot([1,2,5],[7,8,9])
plt.text(x=2.2,#文本x軸坐標
y=8, #文本y軸坐標
s=‘basic unility of text’, #文本內容
rotation=1,#文字旋轉
ha=‘left’,#x=2.2是文字的左端位置,可選’center’, ‘right’, ‘left’
va=‘baseline’,#y=8是文字的低端位置,可選’center’, ‘top’, ‘bottom’, ‘baseline’, ‘center_baseline’
fontdict=dict(fontsize=12, color=‘r’,
family=‘monospace’,#字體,可選’serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, ‘monospace’
weight=‘bold’,#磅值,可選’light’, ‘normal’, ‘medium’, ‘semibold’, ‘bold’, ‘heavy’, ‘black’
)#字體屬性設置
給文本加上背景框
import matplotlib.pyplot as plt
plt.figure(figsize=(5,4),dpi=120)
plt.plot([1,2,5],[7,8,9])
text = plt.text(x=2.2,#文本x軸坐標
y=8, #文本y軸坐標
s=‘basic unility of text’, #文本內容
fontdict=dict(fontsize=12, color='r',family='monospace',),#字體屬性字典#添加文字背景色bbox={'facecolor': '#74C476', #填充色'edgecolor':'b',#外框色'alpha': 0.5, #框透明度'pad': 8,#本文與框周圍距離 })
text.set_color(‘b’)#修改文字顏色
2、添加注釋(matplotlib.pyplot.annotate)
語法:matplotlib.pyplot.annotate(text, xy, *args, **kwargs)
matplotlib.pyplot.annotate結合matplotlib.pyplot.text添加注釋內容。
plt.figure(figsize=(5,4),dpi=120)
plt.plot([1,2,5],[7,8,9])
plt.annotate(‘basic unility of annotate’,
xy=(2, 8),#箭頭末端位置
xytext=(1.0, 8.75),#文本起始位置#箭頭屬性設置arrowprops=dict(facecolor='#74C476', shrink=1,#箭頭的收縮比alpha=0.6,width=7,#箭身寬headwidth=40,#箭頭寬hatch='--',#填充形狀frac=0.8,#身與頭比#其它參考matplotlib.patches.Polygon中任何參數),)
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 6)
y = x * x
plt.plot(x, y, marker=‘o’)
for xy in zip(x, y):
plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords=‘offset points’)
plt.show()