Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: Plotting the bins on x-axis and the average on y-axis

Tags:

r

ggplot2

binning

Suppose that I have a dataframe that looks like this:

data <- data.frame(y = rnorm(10,0,1), x = runif(10,0,1))

What I would like to do is to cut the x values into bins, such as:

data$bins <- cut(data$x,breaks = 4)

Then, I would like to plot (using ggplot) the result in a way that the x-axis is the bins, and the y axis is the mean of data$y data points that fall into the corresponding bin.

Thank you in advance

like image 829
H_A Avatar asked Feb 09 '23 19:02

H_A


1 Answers

You can use the stat_summary() function.

library(ggplot2)
data <- data.frame(y = rnorm(10,0,1), x = runif(10,0,1))
data$bins <- cut(data$x,breaks = 4)
# Points:
ggplot(data, aes(x = bins, y = y)) +
  stat_summary(fun.y = "mean", geom = "point")

# Histogram bars:
ggplot(data, aes(x = bins, y = y)) +
  stat_summary(fun.y = "mean", geom = "histogram")

Here is the picture of the points:

enter image description here

like image 84
maccruiskeen Avatar answered Feb 11 '23 07:02

maccruiskeen