Reputation: 197
I have code
ggplot(bywells[bywells$Well_N == "KRT3",], aes(x = Date_m)) +
geom_line(aes(y = QOM, colour = "Oil, m3/month"))
which draw chart. This code works without any errors. Now I would like to elaborate it in function where bywells
is variable data
and "KRT3"
is variable wellname
, but if I write like this
simple_fun <- function(data, wellname, ...)
{
require("ggplot2", quietly=TRUE)
ggplot(data[data$Well_N == "wellname",], aes(x = Date_m)) +
geom_line(aes(y = QOM, colour = "Oil, m3/month"))
}
after executing function I get error message
Error: Aesthetics must either be length one, or the same length as the dataProblems:QOM, Date_m
when I try
ggplot(data[wellname == Well_N %in% data,], aes(x = Date_m))
I get
Error in match(x, table, nomatch = 0L) : object 'Well_N' not found
Any hints how can I define it as a variable properly?
For example reproducibility I ad small chunk of data sample:
"Well_N";"Date_m";"QOM";"QWM";"QOMT";"BHP";"PRES";"QIW";"THPI";"QFM";"WCT"
"KRT3";2014-06-30;132;525;108;NA;NA;NA;NA;657;79
"KRT3";2014-07-30;36;120;29;NA;NA;NA;NA;156;76
"KRT3";2014-08-30;39;2.6;32.1;NA;NA;NA;NA;41.6;6.25
"KRT3";2014-09-30;211.274;749.362;174.070;NA;NA;NA;NA;960.636;78
"KRT3";2014-10-30;45;45;37.07;NA;NA;NA;NA;90;50
"KRT4";2014-08-30;108.37;1815.358;90.79;NA;NA;NA;NA;1923.73;94
"KRT4";2014-09-30;161.775;202.87;133;NA;NA;NA;NA;364;55
"KRT4";2014-10-30;30;1680;24;NA;NA;NA;NA;1710;98
"KRT4";2014-11-30;31.8;339;26;NA;NA;NA;NA;370.8;91
Type of Well_N
is factor
, Date_m
is POSIXct
, others are num
.
Upvotes: 0
Views: 173
Reputation: 11518
Here is the reproducible data (I've left only three columns which are needed, use function dput
in your future questions):
bywells <-
structure(list(Well_N = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L), .Label = c("KRT3", "KRT4"), class = "factor"), Date_m = structure(c(16251,
16281, 16312, 16343, 16373, 16312, 16343, 16373, 16404), class = "Date"),
QOM = c(132, 36, 39, 211.274, 45, 108.37, 161.775, 30, 31.8
)), class = "data.frame", row.names = c(NA, -9L), .Names = c("Well_N",
"Date_m", "QOM"))
Here is the call without the function:
library(dplyr)
library(ggplot2)
library(magrittr)
qplot(x=Date_m, y=QOM, data = bywells %>% filter(Well_N == "KRT3"), geom="line")
Here is the function:
pfun <- function(data,wellname) {
qplot(x=Date_m, y=QOM, data=data %>% filter(Well_N == wellname), geom="line")
}
with the corresponding call:
pfun(bywells,"KRT3")
Your error was to put the quotes on the variable wellname
in the condition which filters the data. Also your colour setting is not ok, since there is no such color called "Oil, m3/month". Aim for English words such as "red", "blue", see colors()
for more variants. Colour should be set outside aes argument in order for it to work.
Upvotes: 1