library(ggplot2)Program 12
USN
1NT24IS227
RPubs Link
https://rpubs.com/Stephen__/1421968
Steps:
- Step 1: Intsall/Load the required library
- Step 2: Analyze the dataset - IRIS/ mtcars
- Step 3: Define ggplot
- Step 4: add vp layer
- Step 5: Update the title, label
- Step 6: apply the clean theme
- Step 7: Move the legend to the top
Step 1: Intall/Load the requred library
We use ggplot2 library, we have already installed it, so we are directly loading it
Step 2: Analyze the dataset - IRIS/ mtcars
We use iris dataset for violin
tail(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species
145 6.7 3.3 5.7 2.5 virginica
146 6.7 3.0 5.2 2.3 virginica
147 6.3 2.5 5.0 1.9 virginica
148 6.5 3.0 5.2 2.0 virginica
149 6.2 3.4 5.4 2.3 virginica
150 5.9 3.0 5.1 1.8 virginica
head(iris,n=1) Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
tail(iris, n=1) Sepal.Length Sepal.Width Petal.Length Petal.Width Species
150 5.9 3 5.1 1.8 virginica
str(iris)'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
table(iris$Species)
setosa versicolor virginica
50 50 50
p=ggplot(iris, aes(Species, Sepal.Length, fill = Species))
q=ggplot(iris, aes(Species, Sepal.Width, fill = Species))
r=ggplot(iris, aes(Species, Petal.Length, fill = Species))
s=ggplot(iris, aes(Species, Petal.Width, fill = Species))
p;q;r;s;p=p+geom_violin()
q=q+geom_violin()
r=r+geom_violin()
s=s+geom_violin()
p;q;r;s;Step 5: Update the title, label
p=p+labs(
title = 'violin plot showing density of sepal length',
x = 'Species',
y = 'Sepal Length'
)
q=q+labs(
title = 'Violin Plot showing density of sepal width',
x= 'Species',
y = 'Sepal Width'
)
r=r+labs(
title = 'Violin Plot showing density of Petal Length',
x= 'Species',
y = 'Petal Length'
)
s=s+labs(
title = 'Violin Plot showing density of Petal width',
x= 'Species',
y = 'Petal Width'
)
p;q;r;s;Step 6: apply the clean theme
p=p+theme_minimal()
q=q+theme_minimal()
r=r+theme_minimal()
s=s+theme_minimal()
p;q;r;s