R Bars
Bar plots in R are used to display data in rectangular bars. The barplot()
function is used to create both vertical and horizontal bar plots.
Key Topics
Bar Plot Example
# Creating a bar plot
values <- c(5, 10, 15, 20)
names <- c("A", "B", "C", "D")
barplot(values, names.arg = names, main = "Bar Plot Example", col = "blue")
Output:
A bar plot with four bars labeled A, B, C, and D, colored in blue.
Code Explanation: The barplot()
function creates a bar plot with bars representing the values in the values
vector. The names.arg
parameter adds labels to the bars.
Customizing Bar Plot
Bar plots can be customized by changing the color, orientation, and adding labels.
# Horizontal bar plot with custom colors
barplot(values, names.arg = names, main = "Horizontal Bar Plot",
col = c("red", "green", "blue", "yellow"), horiz = TRUE)
Output:
A horizontal bar plot with bars in red, green, blue, and yellow.
Code Explanation: The horiz
parameter is set to TRUE
to create a horizontal bar plot. Colors are specified using a vector in the col
parameter.
Key Takeaways
- Use the
barplot()
function to create bar plots in R. - Bar plots can be oriented vertically or horizontally.
- Colors and labels can be customized for better visualization.