Week 6
Aim:
☛ Create a CSV file having Speed and Distance attributes with 1000 records. Write R program to draw
i) Box plots
ii) Histogram
iii) Line Graph
iv) Multiple line graphs
v) Scatter plot
to demonstrate the relation between the cars speed and the distance.
Solution :
The following CSV file having Speed and Distance attributes with some sample records
CSV file : "speed_distance.csv"
Speed,Distance
90,427
49,155
43,159
75,297
92,430
62,244
.
.
.
.
....
46,158
89,432
55,188
20,37
49,178
To Download complete CSV file with 1000 records : Click Here
R Program: SD_charts.R
# Read the dataset
data <- read.csv("speed_distance.csv")
# Attach variables
attach(data)
# Set up colors
color_speed <- "steelblue"
color_distance <- "tomato"
# i) Box Plots
boxplot(Speed, Distance,
names = c("Speed", "Distance"),
main = "Boxplot of Speed and Distance",
col = c(color_speed, color_distance))
windows()
# ii) Histogram
par(mfrow = c(1, 2))
hist(Speed, col = color_speed, main = "Histogram of Speed", xlab = "Speed", breaks = 20)
hist(Distance, col = color_distance, main = "Histogram of Distance", xlab = "Distance", breaks = 20)
par(mfrow = c(1, 1))
windows()
# iii) Line Graph
plot(Speed, type = "l", col = color_speed, main = "Line Graph - Speed over Records", ylab = "Speed", xlab = "Record Index")
windows()
# iv) Multiple Line Graphs
plot(Speed, type = "l", col = color_speed, ylim = range(c(Speed, Distance)),
main = "Multiple Line Graphs: Speed & Distance",
xlab = "Record Index", ylab = "Value")
lines(Distance, type = "l", col = color_distance)
legend("topright", legend = c("Speed", "Distance"), col = c(color_speed, color_distance), lty = 1)
windows()
# v) Scatter Plot
plot(Speed, Distance,
main = "Scatter Plot: Speed vs Distance",
xlab = "Speed", ylab = "Distance",
col = "darkgreen", pch = 19)
abline(lm(Distance ~ Speed), col = "red", lwd = 2)
Output:
Box Plots
Histogram
Line Graph
Multiple Line Graphs
Scatter Plot
๐ป Run This R Program
Week 6
The selected R program is loaded
automatically into the editor.
Edit the program, provide input if required
and click Run.
The compiler is embedded using OneCompiler.
Your R program runs inside the embedded R environment;
Study Glance does not execute R code directly on your web
server. Programs that draw charts (pie, bar, box plots,
histograms), read a CSV file from your own computer or
install packages may not behave the same way in an online
sandbox. Run those in RStudio or the R console.