Put zero for x axis values - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Put zero for x axis values (/thread-34408.html) |
Put zero for x axis values - quest - Jul-28-2021 Hello, I have this dict: od = OrderedDict([(0, 1), (1, 1), (3, 1), (7, 1), (36, 1)])And I am plotting this array with the following line: plt.bar(range(len(od)), list(od.values()), align='center') plt.xticks(range(len(od)), list(od.keys()),rotation='vertical')IN this example for x axis, I have 0,1,3,7,36. However I don't have 2 between 1 and 3 and I don't have any other numbers between 7 and 36. So I want to update my dict like that: od=([(0, 1), (1, 1),(2,0), (3, 1), (7, 1), (8,0),(9,0),(10,0),(11,0),...(36, 1)])How can I do that? I tried this way: finalarray=np.zeros(60) # or sth larger than max (input dict keys) for k,v in od: print(k,v) finalarray[k]=vAnd I got this error:
RE: Put zero for x axis values - Larz60+ - Jul-29-2021 I think what you wanted was (line 1): od = OrderedDict([(0, 1), (1, 1), (3, 1), (7, 1), (36, 1)])and assuming this code is in same script: finalarray=np.zeros(60) # or sth larger than max (input dict keys) for k,v in od: print(k,v) finalarray[k]=v RE: Put zero for x axis values - quest - Jul-29-2021 (Jul-29-2021, 01:59 AM)Larz60+ Wrote: I think what you wanted was (line 1): Thanks for corrections but I still could not solve my problem RE: Put zero for x axis values - quest - Jul-29-2021 okay, problem has been solved: for k,v in list(od.items()): print(k,v) finalarray[k]=v RE: Put zero for x axis values - DeaD_EyE - Jul-29-2021 I guess there is a better solution for matplotlib to fill the gaps. A function which looks for the gaps and fill them: def continious_keys(mapping, fillvalue=0): last = None for key, value in mapping.items(): if last is None: yield key, value last = key else: while last + 1 < key: last += 1 yield last, fillvalue yield key, value last = keyIt's a generator, so you have to consume it. For example you can use a OrderedDict again. from collections import OrderedDict od = OrderedDict([(0, 1), (1, 1), (3, 1), (7, 1), (36, 1)]) generator = continious_keys(od) new_od = OrderedDict(generator) # <- consumes the generator, creates a new OrderedDictTo make it better visible, I used as fillvalue=math.nan, which is not a number. Example output from repl:
|