manas
manas

Reputation: 471

plotting the bar graph using the data

Hii experts i want to make a beautiful bar plot using the attached data(data.txt). On the x axis i want to plot years such as 2007, 2008 etc from the first column data and on the y axis corresponding second column data.Most importantly, i want to mention only the year such as 2007 2008 only once along the x axis as on the x axis labels doesnot visible due to huge data.

sample data is shown here

2008-05-23  5.1
2008-05-21  6.5
2008-05-26  2.3
2008-06-10  3.7
2008-05-12  6.2
2008-07-06  5.7
2008-07-31  3.0

i tried below :script

import numpy as np
import matplotlib.pyplot as plt
x=np.loadtxt('data.txt')
plt.plot(x)
plt.show()

Upvotes: 0

Views: 182

Answers (3)

Karina
Karina

Reputation: 1280

import pandas as pd

file = pd.read_csv("data.txt", sep='\t')
file['x'] = pd.to_datetime(file['x'], format='%Y/%m/%d')
fig, bx = plt.subplots()
bx.bar(file['x'], file['y'])
bx.set_xlabel('Year')
bx.set_ylabel('Amplitude')

alternatively you can do a workaround (in case if somehow the value shown by the bar graph is not correct), replace

bx.bar(file['x'], file['y'])

with

bx.vlines(file['x'], 0, file['y'])

the year label in the x-axis will fit itself automatically as your data get larger.

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71689

Change the dtype of column x to datetime, then use dt accessor to get the year, then group the dataframe by year and aggregate column y using sum. Now use the plot method to create a bar plot

df.groupby(pd.to_datetime(df['x']).dt.year)['y'].sum().plot(kind='bar');

Resulting bar plot:

enter image description here

Upvotes: 1

burtphil
burtphil

Reputation: 178

the matplotlib documentation is a good place to start: https://matplotlib.org/stable/gallery/index.html

this should work:

import numpy as np
import matplotlib.pyplot as plt
xlabels = ["2007-11-05","2007-11-07",
           "2007-11-07","2008-01-17",
           "2008-02-17","2008-02-18",
           "2008-04-12"]
y = [8.5,8.8,8.3, 8.3, 8.2,4.4,6.5]

x = np.arange(len(xlabels))
fig, ax = plt.subplots()
ax.bar(x, y)
plt.xticks(ticks = x, labels = xlabels, rotation = 90)
plt.show()

Upvotes: 1

Related Questions