2

I have one problem. I am plotting graph using stem function. And my problem is that in variable values there are many zero values. And they make red line under my plotted graph. Is here any possibility how to dont make a marker when value is zero? Thank you.

keys = list(dictionary.keys())
values = list(dictionary.values())
plt.stem(keys,values,'-ro')
plt.show()

enter image description here

4
  • I don't know anything about matplotlib, but maybe you can just filter out the zero values before plotting. Commented Oct 23, 2014 at 19:41
  • So maybe something like filtered = filter(lambda x: x[1]!=0, dictionary.items()). Commented Oct 23, 2014 at 19:47
  • @Hassan Or a dict comprehension, which is what I used (disclaimer: I'm not totally matplotlib savvy either) Commented Oct 23, 2014 at 19:50
  • @matsjoyce Yeah that might be better. +1 looks like you got it. Commented Oct 23, 2014 at 19:52

1 Answer 1

3

One way of doing it (I don't know if it is the matplotlibic way):

  • First filter out the zero values
  • Split the format into two keywords, to stop the bottom circle from being plotted
  • Plot it
import matplotlib.pyplot as plt
import random
dictionary = {i: random.choice([0] * 100 + list(range(100))) for i in range(100)}
new_dict = {i: j for i, j in dictionary.items() if j}
keys = list(new_dict.keys())
values = list(new_dict.values())

plt.stem(keys, values, markerfmt='ro', linefmt='-r')
plt.show()

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments