Exercise-9..Study and Implementation of Data Visulization With Ggplot
Exercise-9..Study and Implementation of Data Visulization With Ggplot
#installing package
#install.packages("ggplot2")
library(ggplot2)
library(plyr)
library(dplyr)
##
##
## summarize
##
## filter, lag
##
#Histogram, Density plots and Box plots are used for visualizing a continuous variable.
#Creating Histogram:
View(iris)
#To change the width of bin in the histograms we can use binwidth in geom_histogram( )
#One can also define the number of bins being wanted, the binwidth in that case will be adjusted automatically.
#Now mpg data will be used for creating the following graphics.
p + geom_bar(stat = "identity")
#Stacked - Position_dodge
p + geom_bar(stat="identity", position=position_dodge())
#Creating BoxPlot
mtcars$cyl = factor(mtcars$cyl)
#Scatter Plot
ggplot(data = mtcars, aes(x = mpg,y = disp,colour = hp)) + geom_point(size = 2.5) + geom_line(aes(y = hp))
#Modifying the axis labels and appending the title and subtitle
#Alternatively
a + labs(color = "Cylinders")
#Combining it all
#Changing the size and color of the Title and the background color.
b + theme_minimal( )
b + theme(panel.background = element_blank())
b + theme(axis.text = element_blank())
b + theme(axis.text.x = element_blank())
b + theme(axis.text.y = element_blank())
c <- ggplot(mtcars,aes(x = mpg, y = disp, color = hp)) +labs(title = "Scatter Plot") +geom_point()
c + theme(legend.position = "top")
#Combining everything.
#To serve the purpose of having 3 colors in the legend we use scale_color_gradient2 with low = "red",mid = "gree
n" and high = "blue" means it divides the entire range(Starting from 0) to the maximum observation in 3 equal par
ts, with first part being shaded as red, central part as green and highest part as blue.
c + theme(legend.position = "bottom") + scale_color_gradientn(colours = c("red","forest green","white","blue"))
#Changing the break points and color scale of the legend together
## Scale for 'colour' is already present. Adding another scale for 'colour',
## Scale for 'colour' is already present. Adding another scale for 'colour',
plot.background = element_rect("orange"))
xlab("Mileage") + ylab("Displacement") +
#To change the x axis limits to 2 to 4, we use scale_x_continuous and scale_y_continuous set the least cut off po
int to 15 and highest cut off point of y axis to 30.
#Faceting.
View(mtcars)
unique(mtcars$carb)
## [1] 4 1 2 3 6 8
#alternatively
# Control the number of rows and columns with nrow and ncol
# Control the number of rows and columns with nrow and ncol
#We store our basic plot in 'z' and thus we can make the additions:
z + facet_grid(cyl ~ .) #row
require(ggrepel)