Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot a one column data frame with ggplot?

Tags:

r

ggplot2

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?

like image 618
Travis Heeter Avatar asked Oct 08 '16 19:10

Travis Heeter


People also ask

What does %>% do in ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.

What is the difference between ggplot and ggplot2?

You may notice that we sometimes reference 'ggplot2' and sometimes 'ggplot'. To clarify, 'ggplot2' is the name of the most recent version of the package. However, any time we call the function itself, it's just called 'ggplot'.


2 Answers

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

like image 86
eipi10 Avatar answered Oct 19 '22 18:10

eipi10


Just try this:

df
   sums
a  122
b   23
c  321

library(ggplot2)
ggplot(df, aes(x=rownames(df), sums)) + geom_bar(stat='identity')

enter image description here

like image 5
Sandipan Dey Avatar answered Oct 19 '22 18:10

Sandipan Dey