Home > Software engineering >  Having trouble to display the graph of a function
Having trouble to display the graph of a function

Time:11-13

I need to do this task with the function f(x) given (f(x) = sin(x) - x*cos(x)):

Generate a figure with two vertical subplots which show, on the top subplot, the function and, on the bottom subplot, the derivative of the function using as input an array with values from -5 to 5 spaced by 0.05. The figure must have the following requirements: The plot must be 5 units wide and 7 units height The two subplots must share the x axis Each subplot must have a title The top subplot must have the ylabel, whereas the bottom subplot must have both xlabel and ylabel It uses two different line styles, sizes and colors x ticks must be in red with fontsize of 12 and rotated of 30°

I did this :

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)

But nothing works, could someone help me please ?

CodePudding user response:

This seems to do what you need:

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

CodePudding user response:

When something goes wrong, it really helps to read Python's error messages. If you don't understand the message, you can google it, which often leads to a useful StackOverflow answer.

For example, the message "AttributeError: 'AxesSubplot' object has no attribute 'ylabel'" leads to resulting plot

  • Related