gpt4 book ai didi

MatplotLib line behind bar plot(条形图后面的MatplotLib线)

转载 作者:bug小助手 更新时间:2023-10-24 20:55:09 46 4
gpt4 key购买 nike



I have the function detailed below. It works perfectly well to produce the bar and line plot for the comparisons I am after but the line is behind the bars. Any ideas on what I am doing wrong?
The lineInput, barInput, and xlabel variables are a pd.DataFrame rows where the others are str or bools.

下面详细介绍了我的功能。它可以很好地为我想要的比较生成条形图和线形图,但线条在栏杆后面。你知道我做错了什么吗?LineInput、barInput和xLabel变量是pd.DataFrame行,其他变量是str或bool。


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()

更多回答

I have tried to use the zorder input into the plots but that does not appear to work either

我尝试在绘图中使用zorder输入,但似乎也不起作用

Your title mentions a boxplot but I only see a bar plot. Which do you mean?

你的标题提到了框图,但我只看到了条形图。你的意思是什么?

apologies - yes you are right it is a bar plot.

抱歉,是的,你是对的,这是一场酒吧阴谋。

Set the zorder of ax rather than line1 so that it's on top of ax2.

设置ax而不是line1的zorder,使其位于ax2之上。

Does this answer your question? How to arrange plots of secondary axis to be below plots of primary axis in matplotlib?

这回答了你的问题吗?如何在matplotlib中将二级轴的绘图安排在主轴的绘图之下?

优秀答案推荐

You can plot the line plot separately and then overlay it on top of the bar plot using zorder. Here's how you can do it:

您可以单独绘制线条图,然后使用zorder将其覆盖在条形图的顶部。以下是你如何做到这一点:


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


def plotLineBarResults(xAxis, lineInput, barInput, lineLabel, barLabel, xlabel, ylabel1, ylabel2, yformat, title,
legend=True, grid=True):
fig, ax1 = plt.subplots()

ax1.set_xlabel(xlabel)
ax1.set_ylabel(ylabel1, color='red')
ax1.bar(xAxis, barInput, label=barLabel, color='blue', alpha=0.7)

ax2 = ax1.twinx()
ax2.plot(xAxis, lineInput, label=lineLabel, color='red', marker='o', linestyle='-', linewidth=2, markersize=6,
zorder=2)
ax2.set_ylabel(ylabel2, color='red')

ax1.set_xticks(range(len(xAxis)))
ax1.set_xticklabels(xAxis, rotation=45, ha="right")

ax1.spines['right'].set_visible(False)
ax1.spines['left'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)

ax1.yaxis.set_major_formatter(FormatStrFormatter(yformat))

if legend:
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='upper left', frameon=False, facecolor='white')

if grid:
ax1.xaxis.grid(True, linestyle='--')
ax1.yaxis.grid(True)

ax1.set_title(title)
plt.tight_layout()
plt.show()

Here's and example/use case:

以下是示例/使用案例:


xAxis = ['A', 'B', 'C', 'D', 'E']
lineInput = [10, 15, 20, 25, 30]
barInput = [5, 12, 8, 18, 10]
lineLabel = 'Line Data'
barLabel = 'Bar Data'
xlabel = 'Categories'
ylabel1 = 'Line Y-Axis'
ylabel2 = 'Bar Y-Axis'
yformat = '%.0f'
title = 'Line and Bar Plot Example'


plotLineBarResults(xAxis, lineInput, barInput, lineLabel, barLabel, xlabel, ylabel1, ylabel2, yformat, title)

This is the output:
enter image description here

以下是输出:


更多回答

Your bar and line axes are swapped, which is why your solution works. The twin axis goes in front. But if they want to keep the same axes order, this won't work.

您的条形轴和线轴是互换的,这就是您的解决方案有效的原因。双子轴在前面。但如果他们想保持相同的轴线顺序,这是行不通的。

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com