How To Plot Bar Graph in R Programming

How To Plot Bar Graph in R Programming

Learn How To Plot Bar Graph in R

Mastering how to plot bar graph in R is a vital step in learning data visualization. Bar graphs are used to represent categorical data, showing comparisons clearly across different groups or variables. They are an essential part of data analysis and interpretation in R programming.

Creating a Bar Graph in R Step by Step

To create a bar graph in R, you can use the barplot() function. It’s a simple yet powerful tool from R’s base plotting system. Start with a numeric vector or a frequency table. Then, add names.arg for labels and col to introduce color for a more engaging chart. Additionally, you can customize axes, main titles, and legends.

Enhancing Visualization with R Base Plotting

Bar graphs are effective when you need to summarize categorical data quickly. Moreover, with just a few lines of code, beginners can explore multiple visual styles. Always focus on readability and color balance. Transitioning from basic plots to detailed visuals will improve both your confidence and analytical insight.

Practice and Analyze Data with Confidence

By practicing regularly, you’ll understand how to plot bar graph in R more efficiently. Furthermore, try combining multiple plots, experimenting with grouped or stacked bar charts. Over time, these skills will enhance your overall understanding of R’s visualization capabilities.

📘 Full Explanation of the R Code


🧩 Line 1: Define subject names

subjects <- c("Mathematics", "Physics", "Chemistry")

What it does:

  • The **c()** function in R combines values into a vector.
  • Here, we are creating a **character vector** containing the names of the three subjects.
  • This vector will be used later to **label the bars** in the bar plot.

Explanation of components:

  • subjects → variable name (vector of subject labels)
  • <- → assignment operator in R (assigns the value on the right to the variable on the left)
  • "Mathematics", "Physics", "Chemistry" → strings representing subject names

So after this line,

subjects = ["Mathematics", "Physics", "Chemistry"].

📊 Line 2–10: Create the bar plot

barplot(
  mean_marks1,
  names.arg = subjects,
  col = c("skyblue", "lightgreen", "lightcoral"),
  main = "Average Marks by Subject",
  xlab = "Subjects",
  ylab = "Mean Marks",
  ylim = c(0, 100)
)

Function Overview:

barplot() is a **base R function** that creates a bar chart (vertical or horizontal) from numeric data.

Argument-by-argument breakdown:

  1. mean_marks1

    • The main numeric vector that you want to plot.
    • Each value in this vector represents the **mean marks** for one subject.
    • Example:
      mean_marks1 <- c(80.16667, 73.5, 81.33333)
  2. names.arg = subjects

    • This argument tells R what names to put **under each bar**.
    • It uses the previously defined subjects vector.
    • So each bar will be labeled as *Mathematics*, *Physics*, and *Chemistry*.
  3. col = c("skyblue", "lightgreen", "lightcoral")

    • Specifies colors for the bars.
    • Each color corresponds to a bar (in order).
    • You can use named colors (like "red", "blue") or hexadecimal color codes (like "#FF5733").
  4. main = "Average Marks by Subject"

    • Sets the **title** at the top of the plot.
    • It helps describe what the graph represents.
  5. xlab = "Subjects"

    • Adds a **label on the x-axis** (horizontal axis).
  6. ylab = "Mean Marks"

    • Adds a **label on the y-axis** (vertical axis).
  7. ylim = c(0, 100)

    • Defines the **range of the y-axis**.
    • Here it starts at 0 and ends at 100, ensuring all marks fit within the visible range.
    • Helps keep the scale consistent (since marks are usually out of 100).

🏷️ Line 11–17: Add labels above the bars

text(
  x = seq_along(mean_marks1),
  y = mean_marks1,
  label = round(mean_marks1, 1),
  pos = 3,
  cex = 0.8
)

Function Overview:

text() adds **text annotations** to a plot — in this case, to display the exact mean values above each bar.

Argument breakdown:

  1. x = seq_along(mean_marks1)

    • seq_along() generates a sequence of numbers from 1 to the length of mean_marks1.
    • Example: if there are 3 means, it returns 1, 2, 3.
    • These are the **x-coordinates** (horizontal positions) where each text label will appear — directly above each bar.
  2. y = mean_marks1

    • These are the **y-coordinates** (vertical positions) for the text labels.
    • Each label will be placed above the corresponding bar height.
  3. label = round(mean_marks1, 1)

    • Specifies the text to display.
    • round(mean_marks1, 1) rounds each mean value to 1 decimal place for cleaner display (e.g., 81.3 instead of 81.33333).
  4. pos = 3

    • Determines where the text is placed relative to the coordinates.
    • pos = 3 means **above** the specified (x, y) point.
    • Other possible values:
      • 1: below
      • 2: left
      • 3: above
      • 4: right
  5. cex = 0.8

    • Controls the **size of the text**.
    • 1 is the default size; smaller values like 0.8 make the text slightly smaller and less cluttered.

✅ Final Output

When you run the entire block:

  1. Three bars appear — one each for Mathematics, Physics, and Chemistry.
  2. Each bar has a different color.
  3. The y-axis shows mean marks from 0 to 100.
  4. The top of each bar shows the numeric mean value (rounded to one decimal).
Bar plot generated by R code showing average subject marks for students

💡 Summary Table

Function Purpose Key Arguments
c() Combine values into a vector "Mathematics", "Physics", "Chemistry"
barplot() Draws the bar chart names.arg, col, main, xlab, ylab, ylim
text() Adds text to plot x, y, label, pos, cex
seq_along() Generates numeric sequence 1:n Used to align text with bars
round() Rounds numeric values Used to simplify numeric labels
Educational Resources Footer