Cesar Hernandez
Cesar Hernandez

Reputation: 135

Plotting 2 continuous variables in barchart using ggplot2

I want to plot two continuous variables using ggplot. Assume I have a dataframe where one column is a ratio between 0 and 1, and the other one is an amount. I want to by able to have a break of the ratio in the x axis using something like

 breaks=seq(0, 5, by = .1)

and in the y axis I want to have the sum of the amount for each break. It would be look like a histogram but the y axis should be the sum of all columns within the break ratio. If I was making a histogram, it would look like this:

 ggplot(data=data, aes(ratio)) + 
 geom_histogram(breaks=seq(0, 1, by = .1), aes(fill=..count..))

Upvotes: 1

Views: 848

Answers (1)

antR
antR

Reputation: 907

Try this example script. x in the script represent the variable you want breaks in and then y represents the variable you would like to sum within those break. End product, variable name "SUM" should have your sums and variable named "facet" should have your breaks that you can plot

library(dplyr)
dataframe1<-data.frame(x=seq(0,1, length.out = 100), y = seq(0,1000, length.out = 100))
x<-mutate(dataframe1,facet = factor(rep(c("0-0.25", "0.25 - 0.50", "0.50 - 0.75", "0.75 - 1.0"), each = length(dataframe1$x)/4)))
x[,"SUM"]<-NA
x$SUM
list1<-as.list(matrix(unique(x$facet),nrow = 4, ncol = 1))
list1[[1]]
i<-1:4
facetfill<-function(i){
  sum1<-sum(x$y[x$facet==list1[[i]]])                      
  x$SUM[x$facet==list1[i]]<-sum1
  x$SUM
  }
for (j in 1:4) {
  x$SUM<-facetfill(j)
  x$SUM
}
x$SUM
x

Upvotes: 1

Related Questions