Tuesday, January 20, 2026

Chapter-1:- Bar Plot in R-programming

Example-1:- Standard/ Basic Bar Chart

You have the final grades (out of 100) for five students in a class. Create a basic bar plot to visualize these scores

Data:-     grades <- c(85, 92, 78, 95, 88)
Student Names:- students <- c("Alice", "Bob", "Charlie", "David", "Eve")

Label the x-axis "Student Name"
Label the y-axis "Score (out of 100)"
Set the main title to "Final Exam Results"
Use a colour of your choice

Code:-
# Data: Monthly sales figures
grades <- c(85, 92, 78, 95, 88)

# Labels for the x-axis
students <- c("Alice", "Bob", "Charlie", "David", "Eve")

# Create the bar plot
barplot(grades,
        names.arg = students,  # Add labels to the x-axis
        main = "Final Exam Results", # Add a title
        xlab = "Student Name", # Label the x-axis
        ylab = "Score (out of 100)", # Label the y-axis
        col = rainbow(length(students))) # Set color


Solution:-

Explanation:- 
  • Here you see in 2nd line and 5th line after grades & students you see <- c here c is compulsory to use to compile the data
  • In 8th line we use all the parameter of barplot, names.arg= use to label on x-axis with student name as you see in above solution image
  • main= use for give the title name (Final Exam Results) , xlab= use to label x-axis (Student Name)
  • col use for colour here rainbow(length(students) means students length is 5. So, 5 different colour use here
  • Also, in result image you can't see all 5 names (Alice, bob, charlie, david, eve)-- you can see david name missing in result, you simply click on zoom option then you can see all names, it basically due to less space.


--> All parameter of barplot()

Essential Data & Layout:-

height

A vector or matrix of numeric values representing bar heights

width

The relative width of each bar (default is 1)

space

The amount of space between bars, as a fraction of the average bar width

names.arg

A vector of names to be plotted under each bar

beside

If TRUE, bars for matrix data are placed side by side; If FALSE (default) they are stacked

horiz

A logical value; if TRUE, bar are drawn horizontally

offset

Shifts the bars vertically (or horizontally if horiz=TRUE) from the axis


Styling & Appearance:-

col

A vector of colors for the bars

border

The color of the border around the bars; set to NA to omit borders

density

The density of shading lines, in lines per inch

angle

The slope of shading lines, given in degrees counter-clockwise

main, sub

Overall and sub-titles for the plot

xlab/ ylab

Labels for the x and y axis


Axes & Scaling:-

xlim/ ylim

Limits for the x and y axes

axes

Logical; if TRUE, a vertical (or horizontal) axis is drawn

axisnames

Logical; if TRUE, bar labels (from names.arg) are drawn

log

String specifying if axis scales should be logarithmic (eg. “y”

cex.axis/ cex.names 

Expansion factors for numeric axis labels and bar names



Advanced Customization for Legend Box (explain later):-

legend.text

A vector of text for a legend; if height is a matrix, this uses the row names by default

args.legend

A list of additional arguments to pass the legend() function

xpd

Logical; if TRUE, allows bars to be drawn outside the plot region

add

Logical; if TRUE, adds the bar plot to an existing plot



Example-2:- How to use barplot parameter

Here I use some parameter like density, space, border, col, names.arg, angle, main, sub, xlab, ylab.
Other Parameter you can use according to your requirement in question

Code:-
# Data
values <- c(10, 25, 15, 30)
names <- c("Q1", "Q2", "Q3", "Q4")

# Basic barplot
barplot(values,
        names.arg = names,
        col = "skyblue",
        space=1,
        border="red",
        angle=20,
        density=50,
        main = "Revenue by Quarter",
        sub= "USD",
        xlab = "Quarter",
        ylab = "Revenue in USD")


Result:-

Explanation:- 
  • density=50 means area shaded of bar , if you increase this value then more area shaded
  • col= for the color of bar like here skyblue (Don't use capital letter)
  • space=1, means bar are place 1-1 space distance away
  • angle=20, means 20 degree angle of line in bar as you can see in bar
  • main = for the title (Here in this eg. Revenue by Quarter)
  • sub= for the subtitle (Here in this eg. USD)
  • xlab= use for label the x axis as you can see "Quarter"
  • ylab= use for label the y axis as you can see "Revenue in USD"
  • For better understanding just copy the code and change the value and try by yourself



Example-3:- Stacked Bar Chart

You have sales data for 3 different product (X,Y,Z) across four different sales region (North, South, East, West). Create a stacked bar plot to compare total sales per region, while showing the contribution of each product.

Data (filled row by row: X then Y then Z:
salesdata <-c (50,45,60,55,   # Product X
                        30,25,40,35,   # Product Y
                        20,30,25,15)   # Product Z

- Organize the data into a matrix using nrow=3 and byrow=TRUE
- Name the rows "Product X", "Product Y", "Product Z".
- Name the column "North", "South", "East", "West"
- Use distinct colors for each product
- Include a legend and main title "Quarterly Product Sales by Region".


Code:-
salesdata <-c (50,45,60,55,   # Product X
               30,25,40,35,   # Product Y
               20,30,25,15)   # Product Z

# Create a matrix (2 rows for products, 3 columns for regions, filled by row)
salematrix <- matrix (salesdata, nrow = 3, byrow = TRUE)

# Add names for clarity
colnames (salematrix) <- c("North", "South", "East", "West")
rownames (salematrix) <- c("Product X", "Product Y", "Product Z")

# Create the stacked bar plot
barplot (salematrix,
         main = "Quaternery sales",
         xlab = "Product",
         ylab = "Region",
         col = rainbow (length (rownames (salematrix))), # Colors for the two products
         legend.text=rownames(salematrix), # Automatically adds legend
         args.legend=list(x="topright", inset=c(-0.2,-0.4)))  #Position the legend box


Solution:-



Explanation:- 
  • In solution image, you not see first 3 line , in these line data written as given in question (you can see in code)
  • In 6th line we have to use matrix, to stacked bar one above another 
  • nrow=3 means height of bar is 3 (you see in image 3 different color product X,Y,Z)
  • byrow=TRUE means if data here:- 50,45,60,55, 30,25,40,35, 20,30,25,15)  then it fill the first row then 2nd then 3rd like that --> means 50 in North, 45 in South, 55 in East, 55 in West like that then repeat
  • In 9th line you see colnames  (these use here to specify the column or row)
  • In 10th line you see rownames mainly row denote here height of bar, which you earlier decide 3 so here 3 different name use
  • I think you have difficulty in understanding the rownames and colnames, for better understanding just copy the code and try yourself how its work, it gives you better idea.
  • Then in 14th line, all parameter which use in barplot - salematrix show the data which we use, col=denote the color which we use, rainbow here denote the rainbow color, which randomly give the color to bar
  • legend.text= Use here to create a seperate dialogue box as you can see with written product X,Y,Z with denote color as we earlier mention 
  • args.legend to place the dialogue box in which position, inset mainly to place at particular position but use "c" before the x,y value



Example-4:- Legend Box
Basically it a seperate box to denote the data of the main chart


Explanation:-
In above image, Pink circle denote the legend box, so there are some parameter by which you can change this box design or data.


All parameter of legend()

Position & Layout:-

x/ y

Coordinates to position the legend. x can also be a keyword like “topright”, “bottomleft”, or “center”

inset

Inset distance from margins as a fraction of the plot region (0 to 1) when using keywords

horiz

Logical; if TRUE, sets the legend items horizontally instead of vertically

ncol

The number of columns for legend items (default is 1)

xjust/ yjust

How the legend is justified relative to its (x,y) location (0=left/top, 0.5=center, 1=right/bottom)


Content & Symbols:-

legend

A vector of text or expressions to appear as labels

fill

Colors used to fill the boxes next to legend text

col

The color of lines and points in the legend

lty/ lwd

Line type and width for lines appearing in the legend

pch

The plotting symbols (points) to appear in the legend

angle/ density

Angle and density of shading lines for legend boxes

pt.bg

Background color for points

pt.cex/ pt.lwd

Size and line width for points


Aesthetics & Styling:-

title

Optional title for the legend box

title.col/ title.adj/ title.font/ title.cex

Customization options for the title’s color, alignment, font and size

cex

Character expansion factor relative to the current par(“cex”) (overall legend size)

text.col/ text.font

Color and font style (1=normal, 2=bold, 3=italic, 4=bold-italic) for the legend text

text.width

Custom width of the legend text in user coordinates

bg

Background color for the entire legend box





Example-5:- In example 3 you see we put legend command in barplot but their is a different way

Code:-
salesdata <-c (50,45,60,55,   # Product X
               30,25,40,35,   # Product Y
               20,30,25,15)   # Product Z

# Create a matrix (2 rows for products, 3 columns for regions, filled by row)
salematrix <- matrix (salesdata, nrow = 3, byrow = TRUE)

# Add names for clarity
colnames (salematrix) <- c("North", "South", "East", "West")
rownames (salematrix) <- c("Product X", "Product Y", "Product Z")

# Create the stacked bar plot
barplot (salematrix,
         main = "Quaternery sales",
         xlab = "Product",
         ylab = "Region",
         col = rainbow (length (rownames (salematrix)))) # Colors for the two products

# Add the legend box separately
legend(x = "topright",                  # Position: "topleft", "topright", "center", etc.
       legend = rownames(salematrix),  # The actual labels for the legend items (MANDATORY)
       title = "Product",              # Optional title for the legend
       col = rainbow(length(rownames(salematrix))), # Colors must match your barplot
       pch = 15,                       # Point character: 15 for a filled square
       bty = "o",                      # Box type: "o" draws a box around it (default)
       cex=0.5,
       inset=c(-0.01,0.1))


Result:- 


Explanation:-
Compare this to example no 3, here in 20th line we add a seperate legend() command, I already explain these thing in code and Result image you can check there. If diffculty in understanding just copy the code from this blog and paste in your Rstudio and see the result difference for better understanding



Example-6:- Another way to use legend box with "fill" command instead of "col"

Code:-
salesdata <-c (50,45,60,55,   # Product X
               30,25,40,35,   # Product Y
               20,30,25,15)   # Product Z

# Create a matrix (2 rows for products, 3 columns for regions, filled by row)
salematrix <- matrix (salesdata, nrow = 3, byrow = TRUE)

# Add names for clarity
colnames (salematrix) <- c("North", "South", "East", "West")
rownames (salematrix) <- c("Product X", "Product Y", "Product Z")

# Create the stacked bar plot
barplot (salematrix,
         main = "Quaternery sales",
         xlab = "Product",
         ylab = "Region",
         col = rainbow (length (rownames (salematrix)))) # Colors for the two products

fillcolor=rainbow(length(rownames(salematrix)))

# Add the legend box separately
legend(x = "topright",                  # Position: "topleft", "topright", "center", etc.
       legend = rownames(salematrix),  # The actual labels for the legend items (MANDATORY)
       title = "Product",              # Optional title for the legend
       fill=fillcolor,                   # Colors must match your barplot
       bty = "o",                      # Box type: "o" draws a box around it (default)
       cex=0.5,
       inset=c(-0.01,0.1))

Result:-


Explanation:- 
  • If we compare this with previous example no 5, here we use a different command "fill" instead of "col" and also no need of use "pch", because "pch" mainly code for different symbol
  • You can use either "fill" or use "pch" and "col" both
  • "bty" mainly for the outline of legend box, there are multiple parameter you can use as you can in the table.
  • “bty” Symbol

    Summary

    o (Default)

    Draws a complete rectangle around the plot (all four sides)

    n

    Suppresses the box entirely (no border)

    L

    Draws only the bottom and left borders (creating an “L” shape

    7

    Draws only the top and right borders

    c

    Draw the top, left, and bottom borders

    u

    Draw the left, bottom and right borders

    ]

    Draw the top, right and bottom borders



Example-7:-  What happen if use use only col but not "pch"

Code:-
salesdata <-c (50,45,60,55,   # Product X
               30,25,40,35,   # Product Y
               20,30,25,15)   # Product Z

# Create a matrix (2 rows for products, 3 columns for regions, filled by row)
salematrix <- matrix (salesdata, nrow = 3, byrow = TRUE)

# Add names for clarity
colnames (salematrix) <- c("North", "South", "East", "West")
rownames (salematrix) <- c("Product X", "Product Y", "Product Z")

# Create the stacked bar plot
barplot (salematrix,
         main = "Quaternery sales",
         xlab = "Product",
         ylab = "Region",
         col = rainbow (length (rownames (salematrix)))) # Colors for the two products


# Add the legend box separately
legend(x = "topright",                  # Position: "topleft", "topright", "center", etc.
       legend = rownames(salematrix),  # The actual labels for the legend items (MANDATORY)
       title = "Product",              # Optional title for the legend
       col=rainbow(length(rownames(salematrix))),                   # Colors must match your barplot
       bty = "o",                       # Box type: "o" draws a box around it (default)
       cex=0.5,
       inset=c(-0.01,0.1))

Result:-


Explanation:- If "pch" not use here as you see in result image , no symbol seen like square but you see in previous example 6 (Mainly "pch" for the different symbol like circle/square)




Example-8:- Compare to previous example no 7 , here we use both "col" and "pch"

Code:-
 salesdata <-c (50,45,60,55,   # Product X
               30,25,40,35,   # Product Y
               20,30,25,15)   # Product Z

# Create a matrix (2 rows for products, 3 columns for regions, filled by row)
salematrix <- matrix (salesdata, nrow = 3, byrow = TRUE)

# Add names for clarity
colnames (salematrix) <- c("North", "South", "East", "West")
rownames (salematrix) <- c("Product X", "Product Y", "Product Z")

# Create the stacked bar plot
barplot (salematrix,
         main = "Quaternery sales",
         xlab = "Product",
         ylab = "Region",
         col = rainbow (length (rownames (salematrix)))) # Colors for the two products


# Add the legend box separately
legend(x = "topright",                  # Position: "topleft", "topright", "center", etc.
       legend = rownames(salematrix),  # The actual labels for the legend items (MANDATORY)
       title = "Product",              # Optional title for the legend
       col=rainbow(length(rownames(salematrix))),                   # Colors must match your barplot
       bty = "o",                       # Box type: "o" draws a box around it (default)
       cex=0.5,
       pch=15,
       inset=c(-0.01,0.1))


Result:-


Explanation:- Here we use both col and pch, and you see square with matching color in legend box

Number

“pch” –Symbol

0

square

1

Circle (Default)

2

Triangle (point up)

3

Plus sign

4

Cross (X)

5

Diamond

6

Inverted triangle

15

Solid square

16

Solid circle

17

Solid triangle (point up)

18

Solid diamond

19

Solid circle (with border)

20

Bullet (smaller solid circle)

21

Filled circle

22

Filled square

23

Filled diamond

24

Filled triangle (point up)

25

Filled triangle (point down)


More information regarding legend box discuss in next chapter:- Chapter:- Bar Chart

Chapter-5:- Scatter Plot in R-programming

 Chapter-5:- Scatter Plot in R-programming Example-1:-  Create a scatter plot of car weight on x-axis and miles per gallon on y-axis by pre-...