iT邦幫忙

0

python spyder ipywidgets使用問題

  • 分享至 

  • xImage

您好:參考網路上範例
不過範例是在colab上做的
我是在spyder做的
結果interact 沒有產生互動拉桿
請問 這是spyder的問題嗎?
或該如何解決

另外,若是IDE問題,那一般開發後,單獨執行,是否也會有問題?

謝謝

import pandas as pd

url = "https://raw.githubusercontent.com/GrandmaCan/ML/main/Resgression/Salary_Data.csv"
data = pd.read_csv(url)

#print(data )
# y = w*x + b
x = data["YearsExperience"]
y = data["Salary"]

#print(x )


#--------------------畫圖
import matplotlib.pyplot as plt
import matplotlib as mpl 
from matplotlib.font_manager import fontManager

fontManager.addfont("../ChineseFont.ttf") #若字體放在上一層目錄
mpl.rc("font", family="ChineseFont") #設定字形

#---------------預測 # y_pred = w*x + b

def plot_pred(w,b):   #
    y_pred=x*w+ b
    plt.plot(x, y_pred, color='blue' ,label="預測線")
    plt.scatter(x, y, marker="x", color="red", label="真實數據")
    plt.title("年資-薪水")   #預設不支援中文
    plt.xlabel("年資")
    plt.ylabel("月薪(千)")
    
    plt.xlim( [0, 12] )  #設定軸的 區間值
    plt.ylim( [-60, 140] ) 
    
    plt.legend()   #把label秀出來
    plt.show()

'''
w=0
b=10

plot_pred(w,b)   
'''
from ipywidgets import interact  #互動元件
interact(plot_pred, w=(-100, 100, 1), b=(-100, 100, 1))


圖片
  熱門推薦
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
zivzhong
iT邦研究生 3 級 ‧ 2025-02-25 03:29:18
最佳解答

感覺可以用 matplotlib.widgets.Slider 來模擬互動(?):

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

# 建立圖形和滑桿
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.25)

# 初始參數
w_init = 1
b_init = 10
y_pred = x * w_init + b_init

# 畫圖
line, = ax.plot(x, y_pred, color='blue', label="預測線")
ax.scatter(x, y, marker="x", color="red", label="真實數據")
ax.set_title("年資-薪水")
ax.set_xlabel("年資")
ax.set_ylabel("月薪(千)")
ax.set_xlim([0, 12])
ax.set_ylim([-60, 140])
ax.legend()

# 建立滑桿
ax_w = plt.axes([0.1, 0.15, 0.65, 0.03])
ax_b = plt.axes([0.1, 0.1, 0.65, 0.03])
slider_w = Slider(ax_w, 'w', -100, 100, valinit=w_init)
slider_b = Slider(ax_b, 'b', -100, 100, valinit=b_init)

# 滑桿事件
def update(val):
    w = slider_w.val
    b = slider_b.val
    line.set_ydata(x * w + b)
    fig.canvas.draw_idle()

slider_w.on_changed(update)
slider_b.on_changed(update)

# 顯示互動圖
plt.show()

noway iT邦研究生 1 級 ‧ 2025-02-26 20:08:03 檢舉

謝謝!

我要發表回答

立即登入回答