How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

To plot a very simple bar chart from an input text file, we can take the following steps −

  • Make empty lists for bar names and heights.

  • Read a text file and iterate each line.

  • Append names and heights into lists.

  • Plot the bar chart using the lists.

  • To display the figure, use show() method.

Sample Data File

First, let's look at our sample data file "test_data.txt" ?

Javed 75
Raju 65
Kiran 55
Rishi 95

Each line contains a name followed by a numeric value separated by a space.

Example

Here's how to read the data and create a bar chart ?

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

bar_names = []
bar_heights = []

for line in open("test_data.txt", "r"):
    bar_name, bar_height = line.split()
    bar_names.append(bar_name)
    bar_heights.append(int(bar_height))

plt.bar(bar_names, bar_heights)
plt.xlabel('Names')
plt.ylabel('Scores')
plt.title('Simple Bar Chart')
plt.show()

How It Works

The code reads each line from the text file, splits it into name and height, then appends them to separate lists. The int() conversion ensures the heights are numeric for proper plotting.

Output

Javed Raju Kiran Rishi 0 50 75 95 Names Scores Simple Bar Chart

Key Points

  • Convert height values to integers using int() for proper plotting

  • Use split() to separate name and value from each line

  • Add labels and title to make the chart more informative

  • The file must be in the same directory as your Python script

Conclusion

This approach provides a simple way to create bar charts from text files. Just ensure your data is properly formatted with names and values separated by spaces, and convert numeric values to appropriate data types.

Updated on: 2026-03-25T19:52:12+05:30

961 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements