English 中文(简体)
ggplot2 - Default Plot in R
  • 时间:2024-12-22

ggplot2 - Default Plot in R


Previous Page Next Page  

In this chapter, we will focus on creating a simple plot with the help of ggplot2. We will use following steps to create the default plot in R.

Inclusion of pbrary and dataset in workspace

Include the pbrary in R. Loading the package which is needed. Now we will focus on ggplot2 package.


# Load ggplot2 
pbrary(ggplot2)

We will implement dataset namely “Iris”. The dataset contains 3 classes of 50 instances each, where each class refers to a type of iris plant. One class is pnearly separable from the other two; the latter are NOT pnearly separable from each other.


# Read in dataset
data(iris)

The pst of attributes which is included in the dataset is given below −

Inclusion of Library and Dataset

Using attributes for sample plot

Plotting the iris dataset plot with ggplot2 in simpler manner involves the following syntax −


# Plot
IrisPlot <- ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) 
   + geom_point()
print(IrisPlot)

The first parameter takes the dataset as input, second parameter mentions the legend and attributes which need to be plotted in the database. In this example, we are using legend Species. Geom_point() imppes scattered plot which will be discussed in later chapter in detail.

The output generated is mentioned below −

Using Attributes For Sample Plot

Here we can modify the title, x label and y label which means x axis and y axis labels in systematic format as given below −


print(IrisPlot + labs(y="Petal length (cm)", x = "Sepal length (cm)") 
   + ggtitle("Petal and sepal length of iris"))
Petal and Sepal Length Of Iris Advertisements