Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add rank to histogram

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 is 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 Coyntry name as x coord and text values of ranks. You can set ecact means instead inside aes(y=Height,...

Finally you get this:

enter image description here

Or this with replaced aesthetics:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading