- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to plot a function with ggplot2 in R?
Plotting a function is very easy with curve function but we can do it with ggplot2 as well. Since ggplot2 provides a better-looking plot, it is common to use it for plotting instead of other plotting functions. To plot a function, we should specify the function under stat_function in ggplot.
Example
Consider the below data frame −
> x<-1:10 > df<-data.frame(x)
Loading ggplot2 package −
> library(ggplot2)
Plotting of functions is as shown below:
> ggplot(df,aes(x))+ + stat_function(fun=function(x) log(x))
> ggplot(df,aes(x))+ + stat_function(fun=function(x) log(x)/x)
Output
> ggplot(df,aes(x))+ + stat_function(fun=function(x) log(x)/(x-3))
Output
> ggplot(df,aes(x))+ + stat_function(fun=function(x) (exp(x)^2)*2)
Output
Advertisements