Search code examples
rggplot2labelgeom-bar

Putting labels on a bar chart in R with ggplot2


I am having a little bit of trouble inserting labels on a bar chart in ggplot2.

So far, I have been able to create the bar chart.

Pizza_bar <- ggplot(Pizza_Data_Research_Rockstar, aes(Number_of_times_eaten_pizza))
Times_eaten_pizza_7_days_bar <- Pizza_bar + geom_bar()
Times_eaten_pizza_7_days_bar

Don't know how to automatically pick scale for object of type tbl_df/tbl/data.frame. Defaulting to continuous.

The challenge becomes labeling the count of the different categories. Since I am newbie at R, I went searching for code examples but keep getting error messages.

ggplot(Pizza_Data_Research_Rockstar, aes(x= Number_of_times_eaten_pizza, y = count))+ 
geom_bar(stat = "identity", fill = "steelblue") + 
geom_text(aes(label=count), vjust=-0.3, size=3.5) + 
theme_minimal()

Don't know how to automatically pick scale for object of type tbl_df/tbl/data.frame. Defaulting to continuous. Don't know how to automatically pick scale for object of type function. Defaulting to continuous. Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 46, 0

That is the closest that I have gotten to adding labels.

Could someone please help? Thank you.

Luis


Solution

  • I really could't understand your data, so I made up my own:

    library(ggplot2)
    
    Days = c("Monday", "Tuesday", "Thursday", "Friday")
    Pizzas = c(40, 50, 10, 25)
    Pizzadf = as.data.frame(cbind(Days, Pizzas))
    Pizzadf$Pizzas = as.numeric(as.character(Pizzadf$Pizzas))
    
    Pizzadf
    #>       Days Pizzas
    #> 1   Monday     40
    #> 2  Tuesday     50
    #> 3 Thursday     10
    #> 4   Friday     25
    
    ggplot(data = Pizzadf, aes(x = Days, y = Pizzas))+ 
      geom_bar(stat = "identity", fill = "steelblue") + 
      geom_text(aes(label=Pizzas), vjust=-0.3, size=3.5) + 
      theme_minimal()
    

    Try to modify and adjust.