【问题标题】:Arrange line in front of bars in Matplotlib plot with double y axes在具有双 y 轴的 Matplotlib 图中的条形前面排列线
【发布时间】:2015-06-11 01:57:27
【问题描述】:

我想绘制一个带有两个 y 轴的图形,我希望左侧 y 轴显示一条线,根据该线对 x 轴进行排序,右侧 y 轴显示条形。我的问题是第二个y轴隐藏了第一个y轴,如图所示。我使用的代码如下:

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

fig, ax1 = plt.subplots()    
ax2 = ax1.twinx()
p1 = ax1.plot(ind, total_facilities, '--bo')
width = 1
p2 = ax2.bar(ind, pdb_facilities, width, color='gray',edgecolor = "none")
plt.xlim([-1,len(total_facilities)])
ax1.set_yscale('symlog')

当我重新排列轴时,我在辅助轴上绘制了蓝线,这条线在灰色条的前面,但随后它令人困惑,因为我希望根据主轴的值对 x 轴进行排序y 轴。有什么办法可以将蓝线放在前面,同时保持在主 y 轴上?

【问题讨论】:

  • 试试 ax1.plot(ind, total_facilities, '--bo', zorder=10)
  • 谢谢,但没用
  • @Sait 但感谢您的评论,我在这里找到了解决方案:matplotlib.1069221.n5.nabble.com/…

标签: python matplotlib plot


【解决方案1】:

发现可以切换次y轴的位置,所以左边绘制次y轴,右边绘制主:

ax2 = ax1.twinx()
p1 = ax2.plot(ind, total_facilities, '--bo')
p2 = ax1.bar(ind, pdb_facilities, width, color='gray',edgecolor = "none")
plt.xlim([-1,len(total_facilities)])
ax2.set_yscale('symlog')
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2019-11-14
    • 1970-01-01
    相关资源
    最近更新 更多