Python Forum
Stacked Barchart from Counter using matplotlib
Thread Rating:
  • 2 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stacked Barchart from Counter using matplotlib
#4
(Mar-31-2017, 04:56 PM)alicarlos13 Wrote: the issue i think lies in it read the I'th value of the counter list list then the internal Counter Collection, but when it goes out to the next i'th value, it loose the track of which bin it is in.

Indeed it does, it plots bars for entire serie, not "piecewise" one by one (technically you can do it by zero-filling remaining bins ...). That was what i meant by one more loop and likely need to reshape your data (but i wasnt sure what do you want).

You should have all data for (0, 1) in one serie/list, data for (1,2) in another and so on. Something like:
Output:
{(0, 1): [9, 99, 189, 301], (1, 2): [8, 99, 256, 0], (1, 5): [0, 0, 0, 473]}
 

You just need to take your "keys/labels", and for each key construct list of values  - for  each Counter in your counter list check if key is in Counter and append either its value or zero. You dont need need to store it in dict, but you should have lists of values and its keys/labels. With dict you dont have fixed order, so if you want specific order of values, you need to sort keys somehow.

I quickly converted your data and plotted it without any effort to beautify it:
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter

counter = [Counter({(0, 1): 9, (1, 2): 8}), Counter({(1, 2): 99, (0, 1): 99}), 
           Counter({(1, 2): 256, (0, 1): 189}), Counter({(1, 5): 473, (0, 1): 301})]
N = len(counter)
 
series = {}
for key in {key for keys in counter for key in keys}:
    series[key] = [(0 if key not in item else item[key]) for item in counter]

fig, ax = plt.subplots()
bottom, x = np.zeros(N), range(N)

for key in series:
    ax.bar(x, series[key], label=key, bottom=bottom)
    bottom += np.array(series[key])
plt.legend()
plt.savefig('boo.png', dpi=200)
[Image: aCwpGUT.png]
Reply


Messages In This Thread
RE: Stacked Barchart from Counter using matplotlib - by zivoni - Mar-31-2017, 06:45 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Enhance my stacked barplot title, and flip legend Clunk_Head 0 1,733 Jul-08-2019, 03:30 AM
Last Post: Clunk_Head
  stacked autoencoder training JohnMarie 0 2,689 Feb-24-2019, 12:23 AM
Last Post: JohnMarie
  [Plot a stacked bar graph using plotly offline mode] niks250891 1 5,242 Apr-22-2018, 02:11 PM
Last Post: niks250891

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020