我有下面详细介绍的函数。它可以很好地为我的比较生成条形图和折线图,但是线条在条形图后面。我做错了什么?lineInput
,barInput
和xlabel
变量是pd.DataFrame
行,其他的是str
或bool
s。
import matplotlib.pyplot as plt
import pandas as pd
def plotLineBarResults(xAxis, lineInput, barInput, lineLabel, barLabel, xlabel, ylabel1,ylabel2, yformat, title,legend = True, grid=True):
fig, ax =plt.subplots()
ax2 = ax.twinx()
ax.set_xticklabels(xAxis,rotation=45, ha="right")
line1 = ax.plot(xAxis,lineInput, label = lineLabel, color = 'red')
line2 = ax2.bar(xAxis, barInput, label = barLabel)
ax.set_title(title)
if legend:
lines = line1+[line2]
labs = [l.get_label() for l in lines]
ax.legend(lines, labs,frameon = False, facecolor = 'white')
if grid:
ax.xaxis.grid(True,linestyle = '--')
ax.yaxis.grid(True)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel1)
ax2.set_ylabel(ylabel2)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.yaxis.set_major_formatter(FormatStrFormatter(yformat))
fig.show()
1条答案
按热度按时间vmjh9lq91#
您可以单独绘制折线图,然后使用
zorder
将其覆盖在条形图的顶部。以下是如何做到这一点:以下是示例/用例:
这是输出:x1c 0d1x