0

I have the following dataframe:

V1 V2 V3 V4 V5
A  0  3  1  0
R  4  2  0  0
Q  0  2  4  0

V1 is the identifier and the residual columns resemble the actual data.

I want to create barplots for every row in this dataframe. I tried using melt to reshape into long format and vectorize the problem but was not succesful. Is there a way that does not require writing a function?

EDIT: This is what I would like to see in the end (just the principle layout):

https://plot.ly/~MattSundquist/11035.png

2
  • Possible duplicate of Grouped bar Graph using barplot
    – user5947301
    Feb 19, 2016 at 22:15
  • I do not want to group them as asked for in the other question. I want to have seperate plots using par
    – Fourier
    Feb 19, 2016 at 22:21

3 Answers 3

2

What about doing it this way?

library(tidyr)
library(dplyr)

df_n <- gather(df, key = V1)
names(df_n) <- letters[1:3]
ggplot(df_n, aes(a, c, fill=b)) + geom_bar(position="dodge", stat="identity")

enter image description here

EDITED version:

Using faceting:

ggplot(df_n, aes(a, c, fill=b)) + geom_bar(position="dodge", stat="identity") + facet_grid(.~a, scales = "free")

enter image description here

3
  • Really nice. But again I require subplots not a single one. Thanks.
    – Fourier
    Feb 19, 2016 at 23:10
  • What about faceting?
    – DatamineR
    Feb 19, 2016 at 23:12
  • I have little experience with R. Sorry for that. I wanted to have some nice subplots and have seen some good use of par(mfrow=c(n,m)). Therefore I imported my data with the read.csvfunction. Appearently, plotting from the data.frame is not that straightforward. Thanks for your input.
    – Fourier
    Feb 19, 2016 at 23:22
0

Is this what you want:

d<-data.frame(V1=c('A','R','Q'),V2=c(0,4,0),
               V3=c(3,2,2),V4=c(1,0,4),V5=c(0,0,0))
rownames(d)<-d[,1]
barplot(t(as.matrix(d[,-1])),beside=T) # barplots for group A, R, Q.
3
  • Thanks a lot. It does plot everything but in one plot. I would like to use par(mfrow=c(2,2)) later on.
    – Fourier
    Feb 19, 2016 at 22:11
  • Then try: par(mfrow=c(2,2)); apply(d[,-1],2,barplot)
    – fishtank
    Feb 19, 2016 at 22:28
  • That generates several plots, as intended, but has all the values in each plot.
    – Fourier
    Feb 19, 2016 at 23:10
0

I did one column only, but you get the idea I think:

df = data.frame(v1 = c('A', 'R', 'Q'), v2 = c(0,4,0))
dat1 = split(df, df$v1)
str(dat1)
lapply(dat1, FUN=function(x) ggplot(data=x, aes(v1, v2)) + geom_bar(stat="identity"))

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.