0

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.

Community
  • 1
  • 1
Astron
  • 1,211
  • 5
  • 20
  • 42

2 Answers2

2

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.

Greg Whittier
  • 3,105
  • 1
  • 19
  • 14
1

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))
surajz
  • 3,471
  • 3
  • 32
  • 38