Home > Software engineering >  Add rank to histogram
Add rank to histogram

Time:10-30

I have a dataset like these which show the height of 10 European countries for men.


Country Height
UK 176
Ireland 175
Cyprus 174
Belgium 179
Netherlands 180
Sweden 178
Norway 181
Spain 173
Italy 171
France 177

I would like to create a histogram which shows the country name in a alphabetic order and shows above the bar the rank of the country.

I started already but got not the solution

ggplot(data, aes(x=Country, y=Height))   geom_line(aes())

CodePudding user response:

First. Here is the data. Please provide the sample dataframe in your future questions.

df <- data.frame(Country = c(
"UK", 
"Ireland", 
"Cyprus", 
"Belgium", 
"Netherlands", 
"Sweden", 
"Norway", 
"Spain", 
"Italy", 
"France"),
Height = c(176, 175, 174, 179, 180, 
178, 181, 173, 171, 177))

Second. I would propose to prepare the data first. Let us add a special column for ranks and transform the Country column to ordered factor:

library(ggplot2)
library(dplyr)
df <- df %>%
    mutate(rnk = rank(Height), Country = factor(Country, ordered = T)) 

Third. Let us plot:

df %>% ggplot(aes(y = rnk, x = Country))  
geom_bar(stat = "identity")  
geom_text(aes(label=rnk), vjust = -1)

In this plot we crate the following layers: the barplot with rank as y coord and Country name as x coord and text values of ranks. You can set exact values of Heights instead of ranks inside aes(y = Height,...

Finally you get this:

enter image description here

Or this with replaced aesthetics:

enter image description here

  •  Tags:  
  • r
  • Related