我需要用給定的函式 f(x) 來完成這個任務 (f(x) = sin(x) - x*cos(x)):
生成一個帶有兩個垂直子圖的圖形,在頂部子圖中顯示函式,在底部子圖中顯示函式的導數,使用一個陣列作為輸入,其中的值從 -5 到 5,間隔為 0.05。該圖必須具有以下要求: 該圖必須是 5 個單位寬和 7 個單位高 兩個子圖必須共享 x 軸 每個子圖必須有一個標題 頂部子圖必須有 ylabel,而底部子圖必須同時有 xlabel 和ylabel 它使用兩種不同的線條樣式、大小和顏色 x 刻度線必須為紅色,字體大小為 12,旋轉 30°
我這樣做了:
def f(x):
return np.sin(x) - x*np.cos(x) #The derivative is equal to x
x = np.arange(-5.0, 5.0, 0.05)
figure, (top, bottom) = plt.subplots(2, sharex=True, figsize = [5.0, 7.0])
top.plot(x, f(x), 'b', linewidth = 5)
top.set_title('Function f(x) = sin(x) - x*cos(x)')
top.ylabel('f(x)')
figure.set_xticks(colors = 'r', fontsize = 12, rotation = 30)
bottom.plot(x, x, 'g-', linewidth = 8)
bottom.set_title('Derivative function of f(x)')
bottom.xlabel('x')
bottom.ylabel('df(x)')
plt.show(figure)
但沒有任何效果,有人可以幫我嗎?
uj5u.com熱心網友回復:
這似乎可以滿足您的需求:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.sin(x) - x*np.cos(x) #The derivative is equal to x
x = np.arange(-5.0, 5.0, 0.05)
figure, (top, bottom) = plt.subplots(2, sharex=True, figsize = [5.0, 7.0])
top.plot(x, f(x), 'b', linewidth = 5)
top.set_title('Function f(x) = sin(x) - x*cos(x)')
top.set_ylabel('f(x)')
plt.tick_params(axis='x', colors = 'r', labelsize = 12, rotation = 30)
bottom.plot(x, x, 'g-', linewidth = 8)
bottom.set_title('Derivative function of f(x)')
bottom.set_xlabel('x')
bottom.set_ylabel('df(x)')
bottom.tick_params(axis='x', colors = 'r')
plt.show()
uj5u.com熱心網友回復:
當出現問題時,閱讀 Python 的錯誤訊息確實很有幫助。如果您不明白該訊息,您可以谷歌它,這通常會導致一個有用的 StackOverflow 答案。
例如,訊息“AttributeError: 'AxesSubplot' object has no attribute 'ylabel'”指向
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/357846.html
標籤:Python matplotlib
