Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put labels over geom_bar for each bar in R with ggplot2

I've found this, How to put labels over geom_bar in R with ggplot2, but it just put labels(numbers) over only one bar.

Here is, let's say, two bars for each x-axis, how to do the same thing?

My data and code look like this:

dat <- read.table(text = "sample Types Number sample1 A   3641 sample2 A   3119 sample1 B   15815 sample2 B   12334 sample1 C   2706 sample2 C   3147", header=TRUE)  library(ggplot2) bar <- ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +    geom_bar(position = 'dodge') + geom_text(aes(label=Number)) 

Then, we'll get: enter image description here

It seems that the number texts are also positioned in the "dodge" pattern. I've searched geom_text manual to find some information, but cannot make it work.

Suggestions?

like image 737
Puriney Avatar asked Aug 18 '12 12:08

Puriney


People also ask

How do I label each bar in a Barplot in R?

To add labels on top of each bar in Barplot in R we use the geom_text() function of the ggplot2 package. Parameters: value: value field of which labels have to display. nudge_y: distance shift in the vertical direction for the label.

What is the difference between Geom_col and Geom_bar?

geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.

How do I rearrange bars in ggplot2?

Reordering in ggplot is done using theme() function. Within this, we use axis. text. x with the appropriate value to re-order accordingly.


1 Answers

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +       geom_bar(position = 'dodge', stat='identity') +      geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25) 

ggplot output

like image 97
rcs Avatar answered Sep 20 '22 14:09

rcs