Boby
Boby

Reputation: 1202

My Plot chart is not working as i expected

izip

Here is the result. As you can see the order is 1,2,4,3 it should be 1,2,3,4. Here how i render it

import csv

import matplotlib.pyplot as plt

time = []
total = []
  
with open('new.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter = ',')
      
    for row in plots:
        time.append(row[0])
        total.append(row[1])
  
plt.plot(time, total)
plt.xlabel('Dates')
plt.ylabel('Transactions')
plt.show()

and here is my csv

2022-08-25,1
2022-08-26,2
2022-08-27,4
2022-08-29,3

How can i fix it ? thanks in advance

Upvotes: 1

Views: 75

Answers (1)

Roman Pavelka
Roman Pavelka

Reputation: 4171

The problem with your code is that the y-values are strings. This simple casting to float would fix that:

import matplotlib.pyplot as plt
import csv

time = []
total = []

with open('new.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter = ',')

    for row in plots:
        time.append(row[0])
        total.append(float(row[1]))

plt.plot(time, total)
plt.xlabel('Dates')
plt.ylabel('Transactions')
plt.show()

But notice there is also the same problem with dates, last two dates are not one day from each other but twice as much. Matplotlib know how to handle datetimes though:

import csv
from datetime import datetime as dt

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

time = []
total = []

with open('new.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter = ',')

    for row in plots:
        time.append(dt.strptime(row[0], "%Y-%m-%d"))
        total.append(float(row[1]))

plt.plot(time, total)
plt.xlabel('Dates')
plt.ylabel('Transactions')

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
plt.gcf().autofmt_xdate()

plt.show()

Little help taken from: Format of datetime in pyplot axis

Upvotes: 2

Related Questions