1

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?

2 Answers 2

8

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

Worked fantastic. Thanks for your help!
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.