如何旋转辅助y轴标签,使其不与y-ticks,matplotlib重叠

hse*_*bie 5 python matplotlib

我正在尝试将我的辅助y标签旋转到270 degrees,但是当我这样做时,它传递了rotate=270参数,它重叠了我的y-tick文本.任何想法如何解决这一问题?

fig, ax = plt.subplots()

ax.plot(df.index,df.tripTime,label='Fishing Effort', marker='D')
ax2=ax.twinx()
ax2.plot(tr.index,tr.cost, 'g',label='Fuel Expenditure', marker='d')

lines = ax.get_lines() + ax2.get_lines()
ax.legend(lines,[line.get_label() for line in lines], loc='lower left')
ax.set_ylim((0, 18))

ax2.set_ylabel('Cost ($)',color='g', rotation=270)

for tl in ax2.get_yticklabels():
    tl.set_color('g')

ax.set_ylabel('Fishing Effort (hrs)')
ax.set_xlabel('Time (days)')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

pmo*_*mos 8

更新:这个答案不是很好,请看评论!

这看起来像一个bug,您应该将其报告给matplotlib的问题跟踪器.

虽然它已得到修复,但快速解决方案是将标签填充设置为更高的值:

ax2.set_ylabel('Cost ($)', color='g', rotation=270, labelpad=15)
Run Code Online (Sandbox Code Playgroud)

结果

  • [tacaswell](https://github.com/tacaswell)在问题跟踪器上指出,正确的解决方案是在调用``set_ylabel``时为新旋转设置适当的垂直对齐,即这里``va ='bottom'``. (2认同)