4
votes

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)

3
This is most emphatically not a histogram. It's a bar plot.Carl Witthoft

3 Answers

11
votes

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

2
votes

you can try this too without creating a dataframe explicitly:

ggplot() + geom_bar(aes(x=seq_along(x),y=x), stat='identity') + xlab('x') + ylab('y')

enter image description here

1
votes

Simple Solution:

barplot(x,xlim = c(0,15), ylim = c(0,10))

xlim and ylim are scaled, depending on the vector length