1

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

Mr. T
  • 11,960
  • 10
  • 32
  • 54
spcs_lay
  • 11
  • 1
  • Change `ax.plot(ind+width/2, [t,t,t,t,t], "r--")` to `ax.axhline(t, color='r', ls='--', label='red line')` to get a line over the full width of the subplot. In general, adding `label=...` to `ax.plot(...., label=...)`, `ax.bar(...., label=...)` and similar functions will cause an element added to the legend. – JohanC Mar 09 '22 at 23:47
  • Also see e.g [the difference between drawing plots using plot, axes or figure](https://stackoverflow.com/questions/37970424/what-is-the-difference-between-drawing-plots-using-plot-axes-or-figure-in-matpl) about using `ax.set_title(...)` instead of `plt.title(...)` etc. – JohanC Mar 09 '22 at 23:50

0 Answers0