-2

This is the image I want to create, however, it should have three legends corresponding to the bars.

bar plot

This is the code:

import numpy as np
import matplotlib.pyplot as plt
x=[1,2,3]
y=[399,499,100]
LABELS = ["node0", "node1", "failed"]
cr = ['g','r','b']
fig,ax = plt.subplots()
ax.bar(x,y,align='center',color=cr, Label='txed, rxed, failed')
plt.xticks(x, LABELS)
plt.legend()
plt.show()
Schorsch
  • 7,761
  • 6
  • 39
  • 65
  • 3
    Could you please clarify what you expect in each of the three legends? Do you have an example sketch of your desired outcome? – Schorsch Mar 24 '16 at 14:24
  • I am new to this website, i tried but could only upload the picture but the picture doesnt directly apperas here, You need to click to the above links of my words to get the image – Linux-Fan85 Mar 24 '16 at 15:29
  • Do you want three legends? Or three legend entries? – Schorsch Mar 24 '16 at 15:58
  • Please take a look at this answer: [How to create custom legend in matplotlib based on the value of the barplot](http://stackoverflow.com/a/18983233/2043505) – Schorsch Mar 24 '16 at 16:03
  • Thank you so much, you made my day. One more thing, do you think is there any easy guide to learn MatPlotLib, on its official website, its all confusing, about libraries etc, I am not a pure computer science guy, how should i approach to learn. There are complex methods, every one uses different way to make a graph. – Linux-Fan85 Mar 24 '16 at 16:15

1 Answers1

0

I think you should plot the bars each one at a time:

import numpy as np
import matplotlib.pyplot as plt
x=[1,2,3]
y=[399,499,100]
LABELS = ["node0", "node1", "failed"]
LEGENDS=['txed', 'rxed', 'failed']
cr = ['g','r','b']
fig,ax = plt.subplots()
for i in range(len(x)):
    ax.bar(x[i],y[i],align='center',color=cr[i], label=LEGENDS[i])
plt.xticks(x, LABELS)
plt.legend()
plt.show()
JPG
  • 2,224
  • 2
  • 15
  • 15
  • Thank you so much for your reply. But i was wondering why have you used arrays here, I always have problem with arrays, can you make the same graph without using arrays please? – Linux-Fan85 Mar 24 '16 at 16:27
  • To which arrays do you refer? I use only lists. You can also write 3 `ax.bar` without the `for` loop, if you want. – JPG Mar 24 '16 at 16:38
  • @Schorsch: You gave me a good solution as the far the number of nodes is 2, but if i am increasing the nodes , the legends are also increasing, I have only 3 kinds of packets, Rxed, Txed and failed, but i have to plot 8 nodes, so with 8 nodes, i only want 3 legends, how can i do it. please help – Linux-Fan85 Mar 25 '16 at 15:27