Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R barplot() Function - Drawing Bar Charts

R barplot() Function - Drawing Bar Charts

R Language Examples R Language Examples

The R barplot() function is used to create bar charts, suitable for showing comparisons of categorical data.

The height of each bar represents the value, often used for comparison among categories.

The syntax of the barplot() function is as follows:

barplot(height, names.arg = NULL, col = NULL,

        main = "", xlab = "", ylab = "", horiz = FALSE)

Parameter Description:

Example

Product sales data

products

<-

c

(

"Product A"

,

"Product B"

,

"Product C"

,

"Product D"

,

"Product E"

)

sales

<-

c

(

120

,

85

,

150

,

90

,

110

)

Vertical bar chart

barplot

(

sales,

        names.

arg

=

products,

        main

=

"Sales Volume of Each Product"

,

        xlab

=

"Product"

,

        ylab

=

"Sales Volume"

,

       

col

=

c

(

"steelblue"

,

"coral"

,

"seagreen"

,

               

"gold"

,

"purple"

)

)

Running the above code displays a colored bar chart comparing the sales volume of each product.

barplot() can also draw grouped bar charts:

Example

Grouped data: sales comparison of two quarters

quarter_data

<-

matrix

(

c

(

120

,

85

,

150

,

90

,

110

,

                         

130

,

90

,

140

,

95

,

125

)

,

                       

nrow

=

2

, byrow

=

TRUE

)

rownames

(

quarter_data

)

<-

c

(

"Q1"

,

"Q2"

)

colnames

(

quarter_data

)

<-

c

(

"A"

,

"B"

,

"C"

,

"D"

,

"E"

)

Grouped bar chart

barplot

(

quarter_data,

        beside

=

TRUE,

       

legend

=

rownames

(

quarter_data

)

,

        main

=

"Product Sales Comparison by Quarter"

,

       

col

=

c

(

"steelblue"

,

"coral"

)

)

Running the above code displays a grouped comparison chart of each product's sales volume across two quarters.

R Language Examples R Language Examples