如何在图中添加图例和编辑线条?

发布于 2025-01-12 20:33:53 字数 1030 浏览 2 评论 0原文

我正在尝试将图例叠加到该图上,但不知道如何操作。我希望图例包含两个条形数据集和两条线。如果可能的话,我还想延长图中的虚线,使它们跨越图形的整个宽度。如果您能提供帮助,我将不胜感激。

目前我有以下内容:

import numpy as np
import matplotlib.pyplot as plt

A_Data=np.array([1, 2.3, 1.6, 4.5, 2.7])
B_Data=np.array([ 1.4, 3.3, 2.7, 4.1, 3.9])


N=5
ind = np.arange(N) 
width = 0.35


#limit values for horizontal lines
t = 4.0
o = 1.0

#plot 
fig, ax = plt.subplots()
plt.title('Test Graph for Stack Overflow')

ax.bar(ind, A_Data, width)
ax.bar(ind+width, B_Data,width)

ax.plot(ind+width/2, [t,t,t,t,t], "r--") #is there a way to have this  stretch the whole width 
of the figure?
ax.plot(ind+width/2, [o,o,o,o,o], "k--")
plt.xticks(ind + width / 2, ('one', 'two', 'three', 'four', 'five'))
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.legend(loc='best') #want this to show bars and lines in legend
fig.savefig("Test graph for stack overflow Q", dpi = 300)

当前图如下

I'm trying to overlay a legend to this plot but am not sure how to. I want the legend to include the two bar data sets and the two lines. I'd also like, if possible, to extend the dotted lines in the graph so they span the whole width of the figure. I'd appreciate advice on both if you could help.

At the moment I have the following:

import numpy as np
import matplotlib.pyplot as plt

A_Data=np.array([1, 2.3, 1.6, 4.5, 2.7])
B_Data=np.array([ 1.4, 3.3, 2.7, 4.1, 3.9])


N=5
ind = np.arange(N) 
width = 0.35


#limit values for horizontal lines
t = 4.0
o = 1.0

#plot 
fig, ax = plt.subplots()
plt.title('Test Graph for Stack Overflow')

ax.bar(ind, A_Data, width)
ax.bar(ind+width, B_Data,width)

ax.plot(ind+width/2, [t,t,t,t,t], "r--") #is there a way to have this  stretch the whole width 
of the figure?
ax.plot(ind+width/2, [o,o,o,o,o], "k--")
plt.xticks(ind + width / 2, ('one', 'two', 'three', 'four', 'five'))
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.legend(loc='best') #want this to show bars and lines in legend
fig.savefig("Test graph for stack overflow Q", dpi = 300)

Current figure is shown below

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文