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

I use Python 2.7 and matplotlib. I have a *.txt data file :

0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014

first column of my file (numbers) should be on axis Y in my bar chart, and the second column from my file (dates) should be on axis OX in my histogram. I only know how to read the file:

OX = []
OY = []

try :
    with open('data.txt', 'r') as openedFile :
        for line in openedFile :
            tab = line.split()
            OY.append(int(tab[0]))
            OX.append(str(tab[1]))
except IOError :
    print("IOError!")

I did read a matplotlib docs but it still doesn't help me. I would also like to add dates I read to my bar chart, to make it look like

this

Could someone please help me?

This question is related to python matplotlib bar-chart

The answer is


This code will do what you're looking for. It's based on examples found here and here.

The autofmt_xdate() call is particularly useful for making the x-axis labels readable.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)

fig.autofmt_xdate()

plt.savefig("figure.pdf")

enter image description here


First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.

To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar() method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.

If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:

Bar diagram plot in Excel

I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to matplotlib

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to increase image size of pandas.DataFrame.plot in jupyter notebook? How to create a stacked bar chart for my DataFrame using seaborn? How to display multiple images in one figure correctly? Edit seaborn legend How to hide axes and gridlines in Matplotlib (python) How to set x axis values in matplotlib python? How to specify legend position in matplotlib in graph coordinates Python "TypeError: unhashable type: 'slice'" for encoding categorical data Seaborn Barplot - Displaying Values

Examples related to bar-chart

matplotlib: plot multiple columns of pandas data frame on the bar chart R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph How to display the value of the bar on each bar with pyplot.barh()? How can I change the Y-axis figures into percentages in a barplot? How to get a barplot with several variables side by side grouped by a factor Stacked Bar Plot in R Setting Different Bar color in matplotlib Python Grouped bar plot in ggplot Simplest way to do grouped barplot R barplot Y-axis scale too short