数直線上に点をプロットするPythonコード

数直線に実数を点としてプロットして表示することをPythonで計算してみよう。

数直線の表示

プロットする数のリストを[]で作成する。

リストの数をmatplotlibモジュールでグラフとして表示する。

Python. 数直線を表示して, 任意の実数を点としてプロットする。

import matplotlib.pyplot as plt
import math

# 数のリスト
numbers = [0, 1, math.pi, math.sqrt(2), math.log(2), math.log(2,10), math.e]

# 数直線の両端の設定
x_min = min(numbers) - 0.5
x_max = max(numbers) + 0.5

plt.figure(figsize=(10, 2))

# 数直線の右側の矢印の表示
plt.annotate(
    '', xy=(x_max, 0), xytext=(x_min, 0),
    arrowprops=dict(arrowstyle='->', color='black', linewidth=2)
)

# 点(数)のプロット
for i, num in enumerate(numbers):
    plt.plot(num, 0, 'o', color='black', markersize=10)
    y_offset = 0.2 if i % 2 == 0 else 0.35  # 上下に交互にラベル表示
    plt.text(num, y_offset, f"{num:.2f}", ha='center')

plt.xticks([])
plt.yticks([])
plt.xlim(x_min - 0.5, x_max + 1)
plt.ylim(-0.5, 0.6)
plt.box(False)
plt.show()

コメントを残す