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.

2 Answers 2

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.

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))

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.