简体   繁体   中英

Python Histogram using matplotlib

I've written a python script that parses a trace file and retrieves a list of objects (vehicle objects) containing the vehicle id, timestep and the number of other vehicles in radio range of a particular vehicle for that timestep:

for d_obj in global_list_of_nbrs:
    print "\t", d_obj.id, "\t", d_obj.time, "\t", d_obj.num_nbrs

The sample output from the test file I am using is:

0   0   1
0   1   2
0   2   0
1   0   1
1   1   2
2   0   0
2   1   2

This can be interpreted as vehicle with id 0 at timestep 0 has 1 neighbouring vehicle, vehicle with id 0 at timestep 1 has 2 neighbouring vehicles (ie in radio range) etc.

I would like to plot a histogram using matplotlib to represent this data but am confused what I should do with bins etc and how I should represent the list (currently a list of objects).

Can anyone please advise on this?

Many thanks in advance.

Here's an example of something you might be able to do with this data set:

Note: You'll need to install pandas for this example to work for you.

n = 10000
id_col = randint(3, size=n)
lam = 10
num_nbrs = poisson(lam, size=n)

d = DataFrame({'id': id_col, 'num_nbrs': num_nbrs})

fig, axs = subplots(2, 3, figsize=(12, 4))

def plotter(ax, grp, grp_name, method, **kwargs):
    getattr(ax, method)(grp.num_nbrs.values, **kwargs)
    ax.set_title('ID: %i' % grp_name)

gb = d.groupby('id')

for row, method in zip((0, 1), ('plot', 'hist')):
    for ax, (grp_name, grp) in zip(axs[row].flat, gb):
        plotter(ax, grp, grp_name, method)

在此处输入图片说明

What I've done is created 2 plots for each of 3 IDs. The top row shows the number of neighbors as a function of time for each ID. The bottom row shows the distribution of the number of neighbors across time.

You'll probably want to play around with sharing axes , axes labelling and all the other fun things that matplotlib offers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM