1

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..))
2
  • It is better to make a categorical variable based on your condition and sum the second variable grouping the first one. You can use the resulting dataset for plotting using regular bar plot. Commented Feb 4, 2018 at 23:18
  • That is true.. I can try that... but I think there is a more direct way to do it within the ggplot statement. I think.. not sure.... Commented Feb 4, 2018 at 23:43

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.