-1

Given a function f(x), how to ?

Generate the graph of the function and its derivative function on a figure with one bottom and top subplots that share the x-axis.
Both axes take their form with an input array with values from min to max that are spaced by 0.5. Each subplot must have a title The top subplot must have the ylabel, whereas the bottom subplot must have both xlabel and ylabel Each subplot shot have different styles of lines (colors, thickness, ...) and x ticks must also be in a different style(specifically the fontsize and rotation).

I did this :

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

But it does not work. How could I fix everything ?

Edited for generalization

2 Answers2

0

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()
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

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 this post. In this case, the correct function name is .set_ylabel(). The difference between the "Object Oriented Interface" and the "old" "plt" interface, can be a bit confusing (it is due to historic reasons). It helps to give the "axes" returned by plt.subplots() a name such as ax_top to more easily figure out how example code maps to your situation.

To set the color, rotation etc. of the ticks, you can use ax.tick_params(axis='x', rotation=30, labelsize=12, labelcolor='red'). This can be a bit tricky, the only way to "know" is to search for it on StackOverflow.

There are many different line styles. They can be set via the linestyle=... keyword. The most common ones also can be part of the code in the third parameter to plot(), e.g. ax.plot(x, y, 'b--') would use a blue dashed line style. (See also the introductory tutorial.)

Also note that plt.show() doesn't get the figure as parameter.

import matplotlib.pyplot as plt
import numpy as np

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, (ax_top, ax_bottom) = plt.subplots(2, sharex=True, figsize=[5.0, 7.0])
ax_top.plot(x, f(x), 'b', linewidth=1)
ax_top.set_title('Function f(x) = sin(x) - x*cos(x)')
ax_top.set_ylabel('f(x)')
ax_bottom.tick_params(axis='x', rotation=30, labelsize=12, labelcolor='red')

ax_bottom.plot(x, x, 'g--', linewidth=2)
ax_bottom.set_title('Derivative function of f(x)')
ax_bottom.set_xlabel('x')
ax_bottom.set_ylabel('df(x)')

plt.tight_layout() # fits the axes and text nicely into the figure
plt.show()

resulting plot

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • Are you sure the other answer is correct? It doesn't use linestyles (only thickness and color). It uses `plt.tick_params()` in a wrong way. With the latest matplotlib version (3.4.3) it throws an error for `plt.show(figure)`. – JohanC Nov 12 '21 at 23:36