gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
python作图怎么让第二个x轴在图像下方
- User
python作图怎么让第二个x轴在图像下方
- Assistant
要让第二个 x 轴在图像下方,需要使用 matplotlib 库中的 twinx() 函数,然后修改第二个 x 轴的位置和标签。示例代码如下:
pythonimport matplotlib.pyplot as plt import numpy as np # 创建子图 fig, ax1 = plt.subplots() # 绘制第一个曲线 x = np.linspace(0, 10, 100) y1 = np.sin(x) ax1.plot(x, y1, 'r-', label='sin') # 添加第二个 y 轴 ax2 = ax1.twinx() # 将第二个 x 轴位置设为图像底部 ax2.spines['bottom'].set_position(('axes', -0.15)) # 设置第二个 x 轴标签 ax2.set_xlabel('x2') # 绘制第二个曲线 y2 = np.cos(x) ax2.plot(x, y2, 'g-', label='cos') # 显示图例 ax1.legend(loc='upper left') ax2.legend(loc='upper right') plt.show()运行结果如下图:
[image: twinx] open
- User
How to make the second x-axis below the image in Python drawing
- Assistant
To make the second x-axis below the image in Python plotting, you need to use the twinx() function in the matplotlib library and then modify the position and label of the second x-axis. Here's an example code:
pythonimport matplotlib.pyplot as plt import numpy as np # Create a subplot fig, ax1 = plt.subplots() # Draw the first curve x = np.linspace(0, 10, 100) y1 = np.sin(x) ax1.plot(x, y1, 'r-', label='sin') # Add the second y-axis ax2 = ax1.twinx() # Set the location of the second x-axis to the bottom of the image ax2.spines['bottom'].set_position(('axes', -0.15)) # Set the label of the second x-axis ax2.set_xlabel('x2') # Draw the second curve y2 = np.cos(x) ax2.plot(x, y2, 'g-', label='cos') # Show the legends ax1.legend(loc='upper left') ax2.legend(loc='upper right') plt.show()The output is shown in the image below:
[image: twinx]