2
                 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.

2
  • Please make sure your question is properly formatted, so it can be understood. Also, provide a minimal working example, so your problem can be reproduced. Commented May 15, 2020 at 19:37
  • To set the height of the bar to equal the value use geom_col() instead. geom_bar() set the height of the bar to the count of the items. Commented May 15, 2020 at 20:26

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. With what I have in the data frame how can I make x = rownames and y = average without doing rownames_to_column?
@LXJ you can use barplot(c) directlly in base R. with tidyverse, you need a column. If you don't want to install tibble, then c$rn <- row.names(c) and then use ggplot(c, aes(x = rn, y = average)) + geom_col()
Great, thanks! If I use rownames_to_column how can I change the order of the names? The bar created didn't have the order I wanted. For example, I want the order to be young, cohoused young, old, cohosued old but the bar has a completely different order.
@LXJ You can change the order with either fct_reorder from forcats or c$rn <- factor(row.names(c), levels = yourcustomorderlevels) where yourcustomorderlevels <- c("young", "cohoused young", "old", "cohosued old")
Thanks @akrun! All of them are very informative suggestions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.