My question may be stupid but I could not solve by my own. I have a data which show the sports activiy by year from 1995 to 2015 like this
Year | Sportsactivity (h) |
---|---|
1995 | 300 |
1996 | 299 |
1997 | 315 |
1998 | 286 |
1999 | 275 |
2000 | 302 |
2001 | 304 |
2002 | 301 |
2003 | 320 |
2004 | 342 |
2005 | 333 |
2006 | 355 |
2007 | 370 |
2008 | 366 |
2009 | 364 |
2010 | 362 |
2011 | 358 |
2012 | 356 |
2013 | 354 |
2014 | 323 |
2015 | 298 |
Now I would like to create a histogram
ggplot(data, aes(x=Year, y=Sportsactivity)) geom_bar(stat="identity")
ggtitle("Sportsactivity with rank the year")
How can I add the rank above every year in the bar chart corresponding to the year?
For example 2007 should have the number one above its bar line
CodePudding user response:
A simple solution:
ggplot(data, aes(x=Year, y=Sportsactivity))
geom_bar(stat="identity")
geom_text(aes(label = nrow(data)-rank(Sportsactivity) 1), size = 10, vjust = 2, colour = "white")
ggtitle("Sportsactivity with rank the year")
CodePudding user response:
With simulated data, here is an example where you use rank
function to rank observations values and geom_text
to add the text with vjust
to adjust on vertical axis.
### Import library
library(ggplot2)
### Data-management
data <- data.frame(Year=1995:2015, Sportsactivity=round(rnorm(21, 310, 15)))
data$rank <- rank(data$Sportsactivity)
### ggplot with geom_text
ggplot(data, aes(x=Year, y=Sportsactivity)) geom_bar(stat="identity")
ggtitle("Sportsactivity with rank the year")
geom_text(aes(label = round(rank,1)), vjust=-.5)
CodePudding user response:
you can do it by dplyr functionalities.
- arrange mutate and row_number() for modification of your data frame
- geom_label for labeling
You can do both within ggplot or modify your data frame first