How build a chart plot with a text column vs number column in matplotlib from a file.txt?

397 views Asked by At

I'm new in python and now I'm trying to do a chart plot in matplotlib from a file with a lot of data that have one number column and a text column in this format:

34 Louis Mathews Sullivan
58 Frederick Milton2
 1 Mario Cruz Muñoz

I would like to have a plot like this

enter image description here

and like this:

enter image description here

Considering that is not data frame, the column of name give me some problems. Can you help me and support about this? Thanks

1

There are 1 answers

1
Quang Hoang On BEST ANSWER

Let's try reading this to a dataframe, split it and plot:

df = pd.read_csv('path_to_file.csv', sep='\t', header=None)

df = df[0].str.extract('^([\d]+)\s+(.+)')
df.columns=['number', 'name']
df['number'] = df['number'].astype(float)
df.plot.bar(x='name', y='number')

Output (for the sample data):

enter image description here

If you want horizontal bar, use plot.barh instead:

df.plot.barh(x='name', y='number')

And you get:

enter image description here