首页 > 解决方案 > 无法显示函数的图形

问题描述

给定一个函数 f(x),如何?

在具有共享 x 轴的一个底部和顶部子图的图形上生成函数及其导数函数的图形。
两个轴都采用输入数组的形式,输入数组的值从最小值到最大值,间隔为 0.5。每个子图必须有标题 顶部子图必须有 ylabel,而底部子图必须同时具有 xlabel 和 ylabel 每个子图镜头都有不同样式的线条(颜色、粗细等),x 刻度也必须在不同的样式(特别是字体大小和旋转)。

我这样做了:

#the function is f(x) while the derivative is df(x)

x = np.arange(min, max, 0.5) #scale

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))
top.ylabel('f(x)')
figure.set_xticks(colors = 'r', fontsize = 12, rotation = 30)

bottom.plot(x, df(x), 'g-', linewidth = 8) 
bottom.set_title('Derivative function of f(x)')
bottom.xlabel('x')
bottom.ylabel('df(x)')

plt.show(figure)

但它不起作用。我怎样才能解决所有问题?

为概括而编辑

标签: pythonmatplotlib

解决方案


这似乎可以满足您的需要:

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()

推荐阅读