Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot vector as barplot

Tags:

r

ggplot2

I have a vector:

x<-c(1,1,1,1,2,3,5,1,1,1,2,4,9)
y<-length(x)

I would like to plot this such that each value is plotted separately instead of plotting counts.

So basically each value should be represented separately in the plot where the length of the x axis is equal to y and each value is plotted on the y axis.

How can this be done using qplot?

for a matrix:

a<-matrix(NA, ncol=3, nrow=100)

a[,1]<-1:100
a[,2]<-rnorm(100)
a[,3]<-rnorm(100)

a<-melt(as.data.frame(a),id.vars="V1")

ggplot(a,aes(seq_along(a),a))+geom_bar(stat="identity")+facet_wrap(V1)

like image 218
user1723765 Avatar asked Dec 09 '22 11:12

user1723765


1 Answers

With ggplot2 use x as y values and make sequence along x values for the x axis.

ggplot(data.frame(x),aes(seq_along(x),x))+geom_bar(stat="identity")

enter image description here

If you have matrix a and you need to make plot for each row then melt it and then use variable for x axis and value for the y axis

a<-melt(as.data.frame(a),id.vars=1)

ggplot(a,aes(variable,value))+geom_bar(stat="identity")+facet_wrap(~V1)

enter image description here

like image 134
Didzis Elferts Avatar answered Jan 03 '23 08:01

Didzis Elferts