Travis Heeter Travis Heeter - 1 month ago 19
R Question

How to plot a one column data frame with ggplot?

I have a data frame like this:

__________
| | sums |
|---+------|
| a | 122 |
|---+------|
| b | 23 |
|---+------|
| c | 321 |
|__________|


*Notice "a","b" and "c" are row names.

I would like to see a plot like this:

___
300 -| | |
200 -| ___ | |
100 -| | | ___ | |
0 -|_|___|_|___|_|___|______
a b c


How can I accomplish that?

Answer

Add the rownames as a column in the data frame and then plot. Here's an example with the built-in mtcars data frame:

library(tibble)
library(ggplot2)

ggplot(rownames_to_column(mtcars[1:3,], var="Model"), 
       aes(x=Model, y=mpg)) +
  geom_bar(stat="identity") +
  theme(axis.text.x=element_text(angle=-90, vjust=0.5, hjust=0))

enter image description here

Comments