Dr.R

Laden...

  

Step by step

Barplot

We use the barplot() function to create a bar chart in R. This function requires at least one argument which is the height of the bar, e.g. 5:

barplot(5)

This leads to a single bar filling out the entire plot.

Using a vector of heights results in multiple bars according to the length of the vector:

x <- c(5,2,3,6,4)
barplot(x)

Note that the x co-ordinates of the bars do not exactly match the integer numbers that one would expect, such as 1, 2, 3, 4 and 5. This shows up when adding an x-axis:

axis(1)

However, we might need those x co-ordinates in order to add error bars or text in form of the respective values. To obtain the actual positions of the bars we can assign the plot to an object, e.g. "bp". This object has now the exact x co-ordinates of the bars:

bp <- barplot(x)
bp
     [,1]
[1,]  0.7
[2,]  1.9
[3,]  3.1
[4,]  4.3
[5,]  5.5

Now we can add some text using the text() function. The required x co-ordinates were taken from object bp, the y co-ordinates from x as well as the lables, and we use pos=1 to determine the text being exactly beneath the given co-ordinates (2: left, 3: above, 4: right, without: exactly on the co-ordinates):

text(bp,x,labels=x,pos=1)

Stacked bars

If x is a matrix, the bars are stacked on top of each other (beside=FALSE, the default) or next to each other (beside=TRUE):

x <- rbind(c(5,2,3,6,4),c(5,8,7,4,6))
x
     [,1] [,2] [,3] [,4] [,5]
[1,]    5    2    3    6    4
[2,]    5    8    7    4    6

par(mfrow=c(1,2))
barplot(x)
barplot(x,beside=TRUE)

This Video (in German) shows more examples and explanations: Barplot R

 

 

War das hilfreich?

Tags

Barplot in R, Balkendiagramm in R, Säulendiagramm in R, verschiedene Farben, Hintergrundfarbe, Fehlerbalken, Standardfehler, Standardabweichung, gestapelt, horizontal, x-Achse, y-Achse, unten, links, oben, rechts, Beschriftung, ohne ggplot, mehrere Plots nebeneinander, mehrere Plots übereinander, mehrere Plots in einer Grafik, Datenanalyse mit R, Hausarbeit mit R, Bachelorarbeit mit R, Masterarbeit mit R