如何在Python中使用mpmath绘图时为坐标轴添加标签?
Adding Axis Labels to mpmath Plots in Python
Hey there! Adding axis labels to your mpmath plots is straightforward once you know that mpmath leverages matplotlib under the hood for rendering. Here are two simple methods to get it done:
Method 1: Pass a Matplotlib Axis to mpmath.plot
This approach gives you full control from the start by creating a matplotlib axis first, then using it for your mpmath plot:
import mpmath as mp import matplotlib.pyplot as plt # Define your actual f(x) here (replace the example below) def f(x): return x**2 # Create a matplotlib figure and axis object fig, ax = plt.subplots() # Plot your functions using mpmath, passing the pre-created axis mp.plot(lambda x: x, f, axes=ax) # Add your custom axis labels ax.set_xlabel('Input Value (x)') # Adjust this text to fit your needs ax.set_ylabel('Function Output') # Display the final plot plt.show()
Method 2: Modify the Plot After Drawing
If you've already plotted using mpmath's default call, you can grab the current matplotlib axis and add labels afterward:
import mpmath as mp import matplotlib.pyplot as plt # Define your actual f(x) here def f(x): return x**2 # Plot directly with mpmath mp.plot(lambda x: x, f) # Get the current active axis ax = plt.gca() # Set your axis labels ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') # Refresh and show the updated plot plt.draw() plt.show()
Quick Tip:
Since mpmath relies on matplotlib for rendering, you can use all standard matplotlib axis customizations here too—like adjusting label font size, color, or adding a plot title with ax.set_title().
内容的提问来源于stack exchange,提问作者Shah Faisal Mazhar Abir
相关产品推荐
相关产品推荐

