matplotlib设置双纵坐标轴
时间: 2023-09-04 16:10:30 浏览: 161
要在matplotlib中设置双纵坐标轴,可以使用twinx()函数创建第二个y轴。首先,创建一个包含两个子图的图形(fig)和轴(ax1和ax2)。在第一个轴(ax1)上使用bar()函数绘制柱状图,设置颜色为蓝色,透明度为0.5,并设置x轴标签和y轴标签。然后,使用twinx()函数创建第二个轴(ax2),并使用plot()函数在其上绘制线条图,设置颜色为红色,并设置y轴标签。最后,使用fig.legend()函数添加图例,并使用plt.show()函数显示图形。以下是一个示例代码:
import matplotlib.pyplot as plt
import numpy as np
X = ["2019-01", "2019-02", "2019-03", "2019-04", "2019-05", "2019-06", "2019-07", "2019-08", "2019-09", "2019-10", "2019-11", "2019-12"]
Y1 = np.random.randint(500, 1000, 12)
Y2 = [None]
for i in range(1, len(Y1)):
Y2.append((Y1[i - Y1[i-1]) / Y1[i-1])
fig, ax1 = plt.subplots()
plt.xticks(rotation=45)
ax1.bar(X, Y1, color="blue", alpha=0.5, label="出货量")
ax1.set_xlabel("月份")
ax1.set_ylabel("出货量(吨)")
ax2 = ax1.twinx()
ax2.plot(X, Y2, color="red", label="环比增长")
ax2.set_ylabel("环比增长")
fig.legend(loc="upper right", bbox_to_anchor=(1, 1), bbox_transform=ax1.transAxes)
plt.show()
这段代码可以创建一个带有双纵坐标轴的图形,其中第一个轴(ax1)绘制了柱状图,表示出货量,第二个轴(ax2)绘制了线条图,表示环比增长。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [Matplotlib绘图双纵坐标轴设置及控制设置时间格式](https://blog.csdn.net/weixin_39716971/article/details/110768926)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [matplotlib绘制双坐标轴(双纵轴)](https://blog.csdn.net/lanhezhong/article/details/108061483)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文