Bethany Jade
Bethany Jade

Reputation: 43

Matplotlib axes confused

I'm trying to figure out where I went wrong with this plot, I'm trying to get the axes to go from 0-1 but this one is going from 0.1-0-1, and I'm not too sure where I'm going wrong. the csv file is in the following format:

dishwasher,60,1,1,0,1,0,0.1

import matplotlib.pyplot as plt
import numpy as np
import csv



x = np.array([1,2,3,4,5,6])
with open('Test 5.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
y1=rows[0][2:]
y2=rows[1][2:]

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.legend()
plt.show()

the plot comes out as followed: enter image description here

The only solution I could think of was to invert the axes or to outline the scale for the y-axis but neither worked

Upvotes: 1

Views: 87

Answers (2)

Ashok Krishna
Ashok Krishna

Reputation: 143

  1. Trying using pandas to import CSV files.

  2. You don't have to explicitly pass x = [1,2,3,...] by default x-axis will take those labels.

sample code:

import pandas as pd
df = pd.read_csv("Test 5.csv")
print(df.columns)

Let's assume your data frame df has two columns (washing_machine & dishwasher). To plot these columns using matplotlib.

plt.plot(df.washing_machine.values, label='Washing Machine')
plt.plot(df.dishwasher.values, label='Dishwasher')
plt.legend()
plt.show()

Hope, this helps. Enjoy coding.

Upvotes: 0

Sheldore
Sheldore

Reputation: 39042

Your y values are most seemingly strings that's why your y-axis is out of order. Convert them to floats before plotting using the following list comprehension way

y1=rows[0][2:]
y2=rows[1][2:]

y1 = [float(i) for i in y1] # <--- convert to float
y2 = [float(i) for i in y2] # <--- convert to float

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')

You can also use a map function as following

y1 = list(map(float, y1))
y2 = list(map(float, y2))

Upvotes: 1

Related Questions