user3314790
user3314790

Reputation: 1

R ggplot2 - creating user defined ranges

I am new to R programming and would appreciate some help using ggplot2

I have a set of values for health information with ages ranging from 0 to 65+. I would like to know how to categorize this into specific age ranges like 0 -10, 11- 20 etc and plot a age_group vs no of doctor visits per year(a variable defined in the dataset).

Thanks!

Upvotes: 0

Views: 309

Answers (1)

ErikJS
ErikJS

Reputation: 43

You need to define categories and then plot them using ggplot2.

I have used the following code to make categories for my own data. You can easily change it to fit your datasets.

library("classInt")
library("RColorBrewer")

brks<-classIntervals(plot.melt2.data$data, n=7, style="fixed", fixedBreaks=c(0.5, 0.8,    0.9, 1.1, 1.2, 2, 5, 10)) #define categories
brks <- round(brks$brks,digits=2) #round
catVar<-findInterval(plot.melt2.data$data, brks, all.inside=TRUE) #assign categories for the data (previously melted using 'melt' function)

PMD<-cbind(plot.melt2.data, catVar) #join data & spatial info

# Create labels from break values
intLabels <- matrix(1:(length(brks)-1))
for(i in 1:length(intLabels )){intLabels [i] <- paste(as.character(brks[i]),"-",as.character(brks[i+1]))}
intLabels[1,1]<-c("< 0.8")
intLabels[7,1]<-c(">5")

#actual plotting step
map4<-ggplot(data = PMD, aes(x = long, y = lat, fill = catVar, group = group)) + 
geom_polygon() + geom_path(colour = "grey", lwd = 0.1) + coord_equal() + labs(x = "LON", y = "LAT", fill = "Legend:") + 
ggtitle("My Plot") +facet_wrap(~variable)  + scale_fill_gradientn(colours=brewer.pal(7, "PiYG"), guide="legend", label=intLabels) # creates a faceted - multi plot, remove the +facet_wrap part for a single plot. 

Upvotes: 2

Related Questions