Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positions and text length of bar plot labels

Tags:

r

label

boxplot

I am having trouble with some labels. I am doing bar plots in r and I am a little shocked there isn't an easy command to just place the values at the top. Anyway, I want these labels to be more centered in the bars and to shorten the significant digits so they will fit within the bar. I would also appreciate any suggestions on how to streamline this.

I have tried options(digits=5) and this did not work for the labels. I have used text(plot.name, tmp, labels= c(tmp) but wanted to try and not use this to make it simpler. I have to remake a lot a plots.

tmp = c(mean(1.0000001:100),mean(100.0000001:200), mean(200.0000001:300), mean(300.0000001:400))

barplot(tmp, names=c("site 1", "site 2", "site 3", "site 4") )

text(1:4, tmp, label=tmp, pos=2, srt=90)
like image 640
Chris Heckman Avatar asked Nov 19 '14 22:11

Chris Heckman


People also ask

How do you label a bar graph in Python?

bar() method we plot the grouped bar chart. Then we use for loop to add a text label in each bar of the bar chart. get_height() method is used to get the height of the bars and to format the text we use f'{value}'. To get the middle of each bar on the x-axis we use get_x() and get_width() method.

What is height in bar plot?

Create barplots with the barplot(height) function, where height is a vector or matrix. If height is a vector, the values determine the heights of the bars in the plot.

How do you display the value of the bar on each bar?

barh(x, height) with x as a list of bar names and height as a list of bar values to create a bar chart. Use the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable. At each iteration, call matplotlib.

How do you add numbers to a bar chart in Python?

Steps Needed: Now use plt. text() function to add value labels to the bar chart in this pass the x and y coordinates which will be i and y[i] which is nothing but the height of the bar and pass y[i] this represents the string which will be displayed on the given co-ordinates i.e, i and y[i].


1 Answers

The digits issue can be solved easily by using round(tmp). As @rawr suggests, use the output of barplot to position the labels. Lastly, if you want to draw numbers above the bar, add xpd=NA to allow the number of the highest bar to be drawn outside the plot region.

bp = barplot(tmp, names=c("site 1", "site 2", "site 3", "site 4") )
# numbers above bars
text(x=bp, y=tmp, labels=round(tmp,0), pos=3, xpd=NA)
# numbers within bars
text(x=bp, y=tmp, labels=round(tmp,0), pos=1)
like image 156
koekenbakker Avatar answered Oct 05 '22 10:10

koekenbakker