Reputation: 21
I'm trying to create a line graph using data from different columns in the same data frame. I can create the initial plot but when I go to add lines()
, nothing shows up.
I've tried creating individual vectors for the data in the columns and using lines()
with instead of pulling it out of the data frame, but that doesn't work, neither does extracting it directly from the data frame.
plot(re_date, date_sub$Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering")
lines(date_sub$Sub_metering_2, col = "red")
lines(date_sub$Sub_metering_3, col = "blue")
(note: the x variable, re_date
is a separate vector I've created after converting the date/time column in the original date_sub
data frame.
That shouldn't have any effect on the y variable?
the initial plot works well, but then no new red or blue lines. When I use the same data for the lines in plot() replacing date_sub$Sub_metering_1
with date_sub$Sub_metering_2
(and _3
respectively) they both create line graphs.
I thought maybe it was because the information was on the y-axis, so I even tried
lines( ,date_sub$Sub_metering_2, col = "red")
.
I realize lines() is missing type = "l" as well. I was running it with the "l", then came across one instructional site that had ommitted it, and thought, oh, well it IS somewhat redundant, so I took it out, and still, same result.
I am new to R and apologize if this is a foolish question.
Upvotes: 2
Views: 28201
Reputation: 1817
In your plot
statement you have a x and y component (re_date, date_sub$Sub_metering_1).
When you call lines
you only provide y. R does not know that you also want
re_date
as x-axis. You have to tell R explicitly because otherwise the x values of the data you want to plot with lines
is simply x=1:length(date_sub$Sub_metering_2)
, i.e. 1, 2, 3, 4,5 ...
Try the following:
plot(re_date, date_sub$Sub_metering_1, type = "l", xlab = "", ylab = "Energy sub metering")
lines(re_date, date_sub$Sub_metering_2, col = "red")
lines(re_date, date_sub$Sub_metering_3, col = "blue")
Upvotes: 3