简体   繁体   中英

Plot list of lists as bar graph Python Matplotlib

I have a list of lists that looks as follows:

[[1,100.1],[2,133.222],[3,198.0]]

I'm trying to use this data to draw a bar graph in matplotlib, where the first element in each element of the list is the x-axis (it's always an integer between 1-1000, no repeats) and the second element is the y-axis value.

I'm using Python 3. How would I plot this?

You need to separate the x values from the y values. This can be done by zip :

First:

import numpy as np
import matplotlib.pypl as plt

Now:

In [263]: lst = [[1,100.1],[2,133.222],[3,198.0]]

In [264]: xs, ys = [*zip(*lst)]

In [265]: xs
Out[265]: (1, 2, 3)

In [266]: ys
Out[266]: (100.1, 133.222, 198.0)

Now draw the bars:

In [267]: plt.bar(xs, ys)

Bar graphs do not set the bars widths automatically. In the current case the width turned out to be fine, but a more systematic way would be to take the differences between the x values, like this:

In [269]: np.diff(xs)
Out[269]: array([1, 1])

Usually you have an equally spaced x values, but this need not be the case. You might want to set the width to the minimum difference between the x values, so the bar graph might be generated like this:

In [268]: plt.bar(xs, ys, width=0.9 * np.min(np.diff(xs)))

I would go for something like this:

import matplotlib.pyplot as plt

data = [[1,100.1],[2,133.222],[3,198.0]]
x = map(lambda x: x[0], data)
y = map(lambda x: x[1], data)

plt.bar(x,y)

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