0

I have a set csv file that looks like this:

tau,rh,temp,
00,100,23,
03,85,25,
06,98,26,
09,100,15,

Now I am know how to plot graphs from a csv file. I have the script below:

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

file=sys.argv[1]
fname = open(file,'rt')
plt.plotfile(fname, ('tau', 'rh', 'tmp'), subplots=False)
plt.show()

and this seems to work fine. However, I want to be able to put the plot the tmp on a separate set of y axes than the rh. I know when to plot multiple plots on multiple axes you have to do the following:

t = np.arange(1, 25.0, 5)
s1 = [1,2,3,4,5]
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('rh', color='b')
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
s2 = [1,2,4,9]
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('tmp', color='r')
ax2.tick_params('y', colors='r')

and you get two plots. What I want to do is have s1 set to the csv values for rh and s2 set to the csv values for tmp in the above example based on reading the csv file. How do I go about doing this?

jms1980
  • 1,017
  • 1
  • 21
  • 37

2 Answers2

0

your code has a couple of issues.

I would use pandas to read the csv just for good practice. But it shld work that way as well.

The plotting part is missing a "fig, ax1 = plt.subplots()" command, and the second part has different lenght arrays for x and y (t is 5 terms and s2 is 4 terms)

Try this:

fig, ax1 = plt.subplots()
t = np.arange(1, 25.0, 5)
s1 = [1,2,3,4,5]
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('rh', color='b')
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
s2 = [1,2,4,9,10]
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('tmp', color='r')
ax2.tick_params('y', colors='r')

hope it helps!

epattaro
  • 2,330
  • 1
  • 16
  • 29
0

You could load the data into arrays first:

data = np.loadtxt(sys.argv[1], delimiter=',', skiprows=1, usecols=(0,1,2))
t = data[:,0]
s1 = data[:,1]
s2 = data[:,2]

and then proceed to plot it. This assumes you know the column indices of your data, not just the column names. It would be better to use pandas though:

import pandas
d = pandas.read_csv(sys.argv[1])

and then plot(d['tau'], d['rh']) and plot(d['tau'], d['temp']) on the axes you set up in place of s1 and s2 in the second part of your code.

Ben Schmidt
  • 401
  • 2
  • 8