My bar chart only prints a single bar from my data

Viewed 59

When using the following data and code my bar char only prints 1 bar, any idea on how to fix this?

life_bar
# A tibble: 6 × 2
  Continent                mn
  <chr>                 <dbl>
1 Africa                 41.1
2 Americas               19.5
3 Eastern Mediterranean  47.0
4 Europe                 15.6
5 South-East Asia        37.7
6 Western Pacific        16.4

Code used;

ggplot(life_bar, aes(x = 'mn')) +
geom_bar(fill = 'green', col = 'black')
2 Answers

You need to specify both x and y variables. x should be Continent and y should be mn. You don't quote the column names.

Also when using geom_bar() you need to specify how the values should be aggregated - in your case geom_bar(stat = "identity"). You can avoid that by using geom_col().

ggplot(life_bar, aes(x = Continent, y = mn)) + 
geom_col()

There's lots of built-in help in R e.g. ?geom_bar and extensive online help too.

Possible solution:

Sample data:

life_bar <- structure(list(...1 = c(1, 2, 3, 4, 5, 6), Continent = c("Africa", 
"Americas", "Eastern Mediterranean", "Europe", "South-East Asia", 
"Western Pacific"), mn = c(41.1, 19.5, 47, 15.6, 37.7, 16.4)), spec = structure(list(
    cols = list(...1 = structure(list(), class = c("collector_double", 
    "collector")), Continent = structure(list(), class = c("collector_character", 
    "collector")), mn = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x0a577cf8>, row.names = c(NA, 
-6L), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"))

Sample code:

(plot<-ggplot(life_bar, aes(x=Continent, y=mn, fill=Continent)) +  
    geom_col(position="dodge", color="black")+
    geom_text(aes(label = mn), 
              position = position_dodge(width=1),
              vjust=1.5, size=5, face="bold")+
    
    labs(x="", y="mn", title="Life bar", fill="")+
    # facet_wrap(~variable)+
    theme_bw() +
    theme(plot.title = element_text(hjust = 0.5,  face="bold", size=20, color="black")) + 
    theme(axis.title.x = element_text(family="Times", face="bold", size=16, color="black"))+
    theme(axis.title.y = element_text(family="Times", face="bold", size=16, color="black"))+
    theme(axis.text.x = element_text( hjust = 1,  face="bold", size=14, color="black") )+
    theme(axis.text.y = element_text( hjust = 1,  face="bold", size=14, color="black") )+
    theme(plot.title = element_text(hjust = 0.5)))

Plot:

enter image description here

Related