Astron
Astron

Reputation: 1221

Generating a matlibplot bar chart from two columns of data

I am trying to build a vertical bar chart based on the examples provided in How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file? and pylab_examples example code: barchart_demo.py.

# a bar chart
import numpy as np
import matplotlib.pyplot as plt

data = """100 0.0
      5 500.25
      2 10.0
      4 5.55
      3 950.0
      3 300.25"""

counts = []
values = []

for line in data.split("\n"):
    x, y = line.split()
    values = x
    counts = y

plt.bar(counts, values)

plt.show()

Current I am receiving the following error: AssertionError: incompatible sizes: argument 'height' must be length 15 or scalar. I am not sure if the plt.bar() function is defined correctly. There may be other issues I have overlooked in trying to replicate the two previously mentioned examples.

Upvotes: 0

Views: 624

Answers (2)

Greg Whittier
Greg Whittier

Reputation: 3185

x, y = line.split() returns a tuple of strings. I believe you need to convert them to ints and floats. You also need values.append(x) and values.append(y).

import numpy as np
import matplotlib.pyplot as plt

data = """100 0.0
      5 500.25
      2 10.0
      4 5.55
      3 950.0
      3 300.25"""

counts = []
values = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    counts.append(float(y))

plt.bar(counts, values)

plt.show()

Given the 100 value in the first line (compared to <= 5 for the rest), it makes for a pretty ugly bar chart though.

Upvotes: 2

surajz
surajz

Reputation: 3611

Maybe you want to do something like

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    counts.append(float(y))

Upvotes: 1

Related Questions