If you read graph #208 you now know what is a barplot and how to compute one using R. This section describes the options you can apply to the barplot function to custom it. Let’s start with the most basic barplot you can, without giving any option:
1 2 3 4 5 6 7 |
# Let's create a vector of data: my_vector=c(3,12,5,18,45) names(my_vector)=c("A","B","C","D","E") # The most basic barplot you can do: # see # for explanation barplot(my_vector) |
Let’s study how to custom colors of the barplot. There are 2 possibilities: applying the same color to every bar (giving one color only), or specifying the color of each bar (giving a vector of color). If vector length is less than number of bars, the color values will be repeated.
1 2 3 4 5 6 7 8 |
# Uniform color: barplot(my_vector, col=rgb(0.2,0.4,0.6,0.6) ) # Color specific for each category: barplot(my_vector, col=c(1,2,3,4,5) ) # Custom the border color of the bar: barplot(my_vector, col=rgb(0.1,0.1,0.1,0.1), border="blue" ) |
Then, it is always important to add classic features, like a title to the chart and to the axis, and specific limit for the axis.
1 2 3 4 5 6 7 |
# Change the classic attribute of plots: png("#209_layout_barplot.png" , width = 480, height = 480 ) barplot(my_vector, col=rgb(0.5,0.1,0.6,0.6), xlab="categories", ylab="values", main="My title" , ylim=c(0,60) ) dev.off() # You can put some texture for each bar # see corresponding graph for density and angle attributes. |
It is really easy to make the barplot horizontal instead of vertical. Use the option las=1 to make the axis labels in the good orientation.
1 2 |
# Horizontal Barplot: barplot(my_vector, col=rgb(0.2,0.4,0.6,0.6), horiz=T , las=1) |
It is possible to control the space between bars and the width of the bars. Can be usefull to represent the number of values behind each bar.
1 2 3 4 5 |
# Control space: barplot(my_vector, col=rgb(0.2,0.4,0.6,0.6), space=c(0.1,0.2,3,1.5,0.3) ) # Control width: barplot(my_vector, col=rgb(0.2,0.4,0.6,0.6), width=c(0.1,0.2,3,1.5,0.3) ) |
Not what you are looking for ? Make a new search ![mediatagger]
Leave a Reply