Skip to content Skip to sidebar Skip to footer

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 exam

Solution 1:

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.

Solution 2:

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

Post a Comment for "Generating A Matlibplot Bar Chart From Two Columns Of Data"