Search code examples
rggplot2geom-bar

How to plot a barplot using ggplot


                 average
Young          0.01921875
Cohoused Young 0.07111951
Old            0.06057224
Cohoused Old   0.12102273

I am using the above data frame to create a histogram or bar and my code is as follows:

C <-ggplot(data=c,aes(x=average))
C + geom_bar()

but the plot is attached here.

enter image description here I would like the bar heights to reflect my data on the y axis instead of where the bar is placed on the x axis, but I don't know what my problem is in the code.


Solution

  • We can create a column with rownames_to_column

    library(dplyr)
    library(tibble)
    library(ggplot2)
    c %>%
        rownames_to_column('rn') %>%
        ggplot(aes(x = rn, y = average)) +
             geom_col()
    

    Or create a column directly in base R

    c$rn <- row.names(c)
    ggplot(c, aes(x = rn, y = average)) +
         geom_col()
    

    Or as @user20650 suggested

    ggplot(data=c,aes(x=rownames(c) , y=average))
    

    NOTE: It is better not to name objects with function names (c is a function)


    In base R, with barplot, we can directly get the plots

    barplot(as.matrix(c))