Below pie chart shows the proportion of cars from the mtcars data set that have different carb values. We have used the pie function to draw the graph and other handful R functions like table to format our data, rainbow to generate a set of colours, such that we have a good visualization. Based on the pie chat, it is clear that most cars have 1,2 and 4 carbs.
# Calculating the frequency of different carb values using table function
mtcars_carb <- table(mtcars$carb)
# Create percent proportion label values
percent_labels <- round(100*prop.table(mtcars_carb),1)
# Create labels for each pie proportion
pie_labels <- paste(percent_labels, "%", sep="")
# R code to create the Pie Chart with rainbow function to generate colors
pie(mtcars_carb,col = rainbow(length(mtcars_carb)), labels = pie_labels , main = 'Pie Chart for mtcars of carb', cex = 0.8)
# adding legend for the pie chart
legend("topright", c("carb-1","carb-2","carb-3","carb-4","carb-6","Carb-8"), cex=0.6, fill= rainbow(length(mtcars_carb)))
Below bar chat shows the number of each gear type in mtcars datase. It appears that most cars have 3 gears.
library(ggplot2)
ggplot(data=mtcars, aes(x=gear)) + geom_bar(stat="count",fill = "#FF66AA")
Next chat is stacked bar chat that shows a graph of the number of each gear type and how they are further divided out by cyl.It appears that many cars with 8 cyl have 3 gears. It is also clear that most of cars with 4 cyls, each has 4 gears
#Calculate the frequency of different carb values and numer of cylinders using table function
gear_cyl <- table(mtcars$cyl, mtcars$gear)
#R code to create stacked bar graph
barplot(gear_cyl, main = "Stacked Bar plot for mtcars distribution by Gears Vs Cyl", xlab = "Number of Gears",ylab= "Number of Cylinder", col = c("red", "green", "yellow"), legend = rownames(gear_cyl))
In below chat, we have a scatter plot showing the relationship between wt and mpg.Based on the scatter plot, it appears that when weight incleases mpg decreases and vice versa.
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()+ geom_line() +
ggtitle("Relationship between wt and mpg") +
stat_smooth(method = "loess", formula = y ~ x, size = 1, col = "red")
Here we’re show a graph that visualize the Car Distribution by Gears and Cylinder. We see that, most of 3 gears cars have 8 cylinders, and 5 gears cars have the same number of 4 and 6 cylinders. And no car with 4 gears has 8 cylinder.
# Grouped Bar Plot
counts <- table(mtcars$cyl, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and Cyl",
xlab="Number of Gears", col=c("green","yellow","red"),ylab= "Number of Cylinder",
legend = rownames(counts), beside=TRUE)