Atius
Atius

Reputation: 191

(R) line in qplot, mean of y for every x

I am trying to make a qplot in R. I know I could reformat my data but I want to try to make it in the qplot as I plan, at a later date to connect it to Shiny.

Before the problem, this is my data:

   Date    |    Price    |    Postnr
2016-08-01      5000           101
2016-08-01      4300           103
2016-07-01      7000           105
2016-07-01      4500           105
2016-07-01      3000           103
2016-06-01      3900           101
2016-06-01      2700           103
2016-06-01      2900           105
2016-05-01      7100           101

I am trying to create a graph using plot lines. I want to group using Postnr.

My problem is: I want the Date to be on the X-axis, Price on the Y, the plot point to be created by getting the average Price on each day but I have no idea how to go about creating it with in the qplot itself.

-Edit- Included reproducable data

mydata <- structure(list(Date = structure(c(4L, 4L, 3L, 3L, 3L, 2L,
2L, 2L, 1L), .Label = c("2016-05-01", "2016-06-01", "2016-07-01",
"2016-08-01"), class = "factor"), Price = c(5000L, 4300L, 7000L, 
4500L, 3000L, 3900L, 2700L, 2900L, 7100L), Postnr = c(101L, 103L, 
105L, 105L, 103L, 101L, 103L, 105L, 101L)), .Names = c("Date", 
"Price", "Postnr"), row.names = c(NA, 9L), class = "data.frame")

Upvotes: 2

Views: 269

Answers (2)

Atius
Atius

Reputation: 191

After Ian Fellows got me on the right path I finally found what I was looking for:

ggplot(data = mydata,
  aes(x = Date, y = Price, colour = Postnr, group=Postnr)) +
      stat_summary(fun.y=mean, geom="point")+
      stat_summary(fun.y=mean, geom="line")

Upvotes: 1

user4148072
user4148072

Reputation:

Is this the idea you are looking for, @Atius?

date = runif(100,0,10)+as.Date("1980-01-01")
Price = runif(100,0,5000)
Postnr = runif(100,101,105)

dataFrame =data.frame(date=date, Price=Price, Postnr=Postnr)


d <- ggplot(dataFrame, aes(date, Price))
d + geom_point()
d + stat_summary_bin(aes(y = Postnr), fun.y = "mean", geom = "point")

Upvotes: 0

Related Questions