Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R with ggplot2 horizontal line for average

Tags:

r

ggplot2

average

I've my script which reads data from csv file. I'am calculating average but I would like to see average on graph as horizontal line.

avg = myData$Electricity.Costs
mean(avg)

ggplot(data = myData, 
       aes(x = Date, y = Electricity.Costs, 
           group = Budget.Plan.Monthly.Amount, colours = "Budget.Plan.Monthly.Amount")) + 
   geom_line() + 
   geom_point(aes(colour = Budget.Plan.Monthly.Amount))

Could you please give me some advice?

like image 240
Karol Avatar asked Apr 04 '16 22:04

Karol


People also ask

How do I make a horizontal line in ggplot2?

Example: To add the horizontal line on the plot, we simply add geom_hline() function to ggplot2() function and pass the yintercept, which basically has a location on the Y axis, where we actually want to create a vertical line. Here we set 20 to the xintercept.

How do I add a line in ggplot2?

To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a wide vertical line with different color then lwd and colour argument will be used. The lwd argument will increase the width of the line and obviously colour argument will change the color.

How do you add a mean line in R?

In the R Language, we can do so by creating a mean vector by using the group_by() and summarise() function. Then we can use that mean vector along with the geom_hline() function of the ggplot2 package to create a line by the mean point colored by the group.

How do you add a mean in ggplot2?

Add Mean Values to Boxplot with stat_summary() In ggplot2, we can use stat_summary() function to cmpute new summary statistics and add it to the plot. In this example, we compute mean value of y-axis using fun. y argument in stat_summary() function.


1 Answers

ggplot(data = myData, 
   aes(x = Date, y = Electricity.Costs, 
       group = Budget.Plan.Monthly.Amount, colours = "Budget.Plan.Monthly.Amount")) + 
geom_line() + 
geom_point(aes(colour = Budget.Plan.Monthly.Amount))+
geom_hline(yintercept = mean(avg))
like image 77
adaien Avatar answered Oct 12 '22 00:10

adaien