Pythonのmatplotlibライブラリを使用して、グラフの表示範囲を設定する方法について説明します。具体的には、xlim
とylim
関数を使用して、x軸とy軸の表示範囲を設定します。
xlimとylimの基本的な使い方
xlim
とylim
は、それぞれx軸とy軸の表示範囲を設定するための関数です。
以下に、基本的な使い方を示します。
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, np.pi * 2)
ax.set_ylim(-2, 2)
ax.grid()
plt.show()
このコードでは、set_xlim
とset_ylim
関数を使用して、x軸とy軸の表示範囲を設定しています。
表示範囲の取得
表示範囲を取得するには、get_xlim
とget_ylim
関数を使用します。
以下に、表示範囲の取得方法を示します。
x = np.linspace(0, 10, 1000)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.grid()
plt.show()
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
print(f"x: [{xmin}, {xmax}], y: [{ymin}, {ymax}]")
このコードでは、get_xlim
とget_ylim
関数を使用して、x軸とy軸の表示範囲を取得しています。
以上が、Pythonのmatplotlibライブラリを使用して、グラフの表示範囲を設定する方法についての説明です。これらの関数を使うことで、グラフの表示範囲を自由に設定することができます。.