1

I am trying to plot number of sales on Y axis against the dates on the X axis. I can't seem to work out a way to do the dates on the X axis. If i change the dates to a float, it I can plot it but I still cannot figure out a way to plot the date format.

import matplotlib.pyplot as plt
import csv

x = []
y = []

with open('book1.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        x.append(float(row[0]))
        y.append(float(row[1]))

plt.plot(x,y, label='Loaded from file!')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

My csv looks something like:

1/1/2019,7980.185714
2/1/2019,9478.297619
3/1/2019,9282.166667
4/1/2019,6900.833333
5/1/2019,5563.716667

If I change the dates to a float format, I get this graph: enter image description here

2 Answers 2

1

You need change the type of x to datetime :

import matplotlib.pyplot as plt
import csv
import datetime as dt

x = []
y = []
with open('book1.csv','r') as csvfile:
  plots = csv.reader(csvfile, delimiter=',')
  for row in plots:
      x.append(dt.datetime.strptime(row[0],'%m/%d/%Y').date())
      y.append(float(row[1]))
plt.plot(x,y, label='Loaded from file!')
plt.xlabel('x')
plt.xticks(x, x, rotation=90)
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!. How would I change the date labels interval to daily? Because right now its labeling the date every 4 days.
0

sales are declining. Set the date as an index then plot the Sales

txt="""1/1/2019,7980.185714
2/1/2019,9478.297619
3/1/2019,9282.166667
4/1/2019,6900.833333
5/1/2019,5563.716667"""

from io import StringIO
f = StringIO(txt)
df = pd.read_table(f,sep =',')
df.columns=['Date','Sales']
df['Date']=pd.to_datetime(df['Date'])
df.set_index('Date',inplace=True)
plt.title("Sales")
plt.plot(df)
plt.xticks(rotation=90)
plt.show()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.