Phần 13: Đặt giới hạn X và Y – Matplotib Basic

1. Khái niệm :
Matplotlib tự động đi từ những giá trị tối thiểu và lớn nhất của các biến được hiển thị dọc theo trục x, y (và trục z trong trường hợp biểu đồ 3D) của 1 biểu đồ. Tuy nhiên, có thể đặt giới hạn 1 cách rõ ràng bằng việc dùng hàm set_xlim () và set_ylim ().
Trong biểu đồ sau, các giới hạn được tự động chia tỷ lệ của trục x và y được hiển thị:
import matplotlib.pyplot as plt
fig = plt.determine()
a1 = fig.add_axes([0,0,1,1])
import numpy as np
x = np.arange(1,10)
a1.plot(x, np.exp(x))
a1.set_title('exp')
plt.present()
Hiện tại chỉnh giới hạn trên trục x thành (0 tới 10) và trục y (0 tới 10000) –
import matplotlib.pyplot as plt
fig = plt.determine()
a1 = fig.add_axes([0,0,1,1])
import numpy as np
x = np.arange(1,10)
a1.plot(x, np.exp(x),'r')
a1.set_title('exp')
a1.set_ylim(0,10000)
a1.set_xlim(0,10)
plt.present()
2. Ví dụ :
Ví dụ 1 : Broken Barh
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors='tab:blue')
ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),
facecolors=('tab:orange', 'tab:inexperienced', 'tab:purple'))
ax.set_ylim(5, 35)
ax.set_xlim(0, 200)
ax.set_xlabel('seconds since begin')
ax.set_yticks([15, 25])
ax.set_yticklabels(['Bill', 'Jim'])
ax.grid(True)
ax.annotate('race interrupted', (61, 25),
xytext=(0.8, 0.9), textcoords='axes fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
fontsize=16,
horizontalalignment='proper', verticalalignment='high')
plt.present()
Ví dụ 2 : CSD Demo
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(2, 1)
# make just a little further house between the subplots
fig.subplots_adjust(hspace=0.5)
dt = 0.01
t = np.arange(0, 30, dt)
# Fixing random state for reproducibility
np.random.seed(19680801)
nse1 = np.random.randn(len(t)) # white noise 1
nse2 = np.random.randn(len(t)) # white noise 2
r = np.exp(-t / 0.05)
cnse1 = np.convolve(nse1, r, mode='identical') * dt # coloured noise 1
cnse2 = np.convolve(nse2, r, mode='identical') * dt # coloured noise 2
# two alerts with a coherent half and a random half
s1 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse1
s2 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse2
ax1.plot(t, s1, t, s2)
ax1.set_xlim(0, 5)
ax1.set_xlabel('time')
ax1.set_ylabel('s1 and s2')
ax1.grid(True)
cxy, f = ax2.csd(s1, s2, 256, 1. / dt)
ax2.set_ylabel('CSD (db)')
plt.present()
Ví dụ 3 : EventCollection Demo
import matplotlib.pyplot as plt
from matplotlib.collections import EventCollection
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
# create random information
xdata = np.random.random([2, 10])
# break up the information into two elements
xdata1 = xdata[0, :]
xdata2 = xdata[1, :]
# kind the information so it makes clear curves
xdata1.kind()
xdata2.kind()
# create some y information factors
ydata1 = xdata1 ** 2
ydata2 = 1 - xdata2 ** 3
# plot the information
fig = plt.determine()
ax = fig.add_subplot(1, 1, 1)
ax.plot(xdata1, ydata1, colour='tab:blue')
ax.plot(xdata2, ydata2, colour='tab:orange')
# create the occasions marking the x information factors
xevents1 = EventCollection(xdata1, colour='tab:blue', linelength=0.05)
xevents2 = EventCollection(xdata2, colour='tab:orange', linelength=0.05)
# create the occasions marking the y information factors
yevents1 = EventCollection(ydata1, colour='tab:blue', linelength=0.05,
orientation='vertical')
yevents2 = EventCollection(ydata2, colour='tab:orange', linelength=0.05,
orientation='vertical')
# add the occasions to the axis
ax.add_collection(xevents1)
ax.add_collection(xevents2)
ax.add_collection(yevents1)
ax.add_collection(yevents2)
# set the boundaries
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.set_title('line plot with information factors')
# show the plot
plt.present()
Ví dụ 4 : Join Styles và Cap Styles
Ví dụ này minh họa những kiểu nối và kiểu mũ có sẵn.
Cả 2 đều được dùng trong Line2D và các Bộ sưu tập khác nhau từ matplotlib.collections cũng như là những hàm tạo nên những bộ sưu tập này, ví dụ: âm mưu.
a. Join Styles :
import numpy as np
import matplotlib.pyplot as plt
def plot_angle(ax, x, y, angle, model):
phi = np.radians(angle)
xx = [x + .5, x, x + .5*np.cos(phi)]
yy = [y, y, y + .5*np.sin(phi)]
ax.plot(xx, yy, lw=12, colour='tab:blue', solid_joinstyle=model)
ax.plot(xx, yy, lw=1, colour='black')
ax.plot(xx[1], yy[1], 'o', colour='tab:purple', markersize=3)
fig, ax = plt.subplots(figsize=(8, 6))
ax.set_title('Join model')
for x, model in enumerate(['miter', 'round', 'bevel']):
ax.textual content(x, 5, model)
for y, angle in enumerate([20, 45, 60, 90, 120]):
plot_angle(ax, x, y, angle, model)
if x == 0:
ax.textual content(-1.3, y, f'{angle} levels')
ax.textual content(1, 4.7, '(default)')
ax.set_xlim(-1.5, 2.75)
ax.set_ylim(-.5, 5.5)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.present()
b. Cap types :
fig, ax = plt.subplots(figsize=(8, 2))
ax.set_title('Cap model')
for x, model in enumerate(['butt', 'round', 'projecting']):
ax.textual content(x, 1, model)
xx = [x, x+0.5]
yy = [0, 0]
ax.plot(xx, yy, lw=12, colour='tab:blue', solid_capstyle=model)
ax.plot(xx, yy, lw=1, colour='black')
ax.plot(xx, yy, 'o', colour='tab:purple', markersize=3)
ax.textual content(2, 0.7, '(default)')
ax.set_ylim(-.5, 1.5)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)