annndrey
annndrey

Reputation: 1788

How to plot one variable in ggplot?

I'm searching but still can't find an answer to a quite simple question - how can we produce a simple dot plot of one variable with ggplot2 in R?

with plot command this is very simple:

plot(iris$Sepal.Length, type='p')

But when I'm trying to pass one variable to qplot and specifying geom="point", I'm getting an error "Error in UseMethod("scale_dimension")".

Simple one-variable plot

How can we make a plot like this but with ggplot2?

Upvotes: 43

Views: 77117

Answers (5)

Sven Hohenstein
Sven Hohenstein

Reputation: 81733

You can manually create an index vector with seq_along.

library(ggplot2)

qplot(seq_along(iris$Sepal.Length), iris$Sepal.Length)

enter image description here

Upvotes: 58

se7entyse7en
se7entyse7en

Reputation: 4294

An alternative to using qplot and without specifying the data param:

ggplot(mapping=aes(x=seq_along(iris$Sepal.Length), y=iris$Sepal.Length)) +
    geom_point()

or:

ggplot() +
    geom_point(aes(x=seq_along(iris$Sepal.Length), y=iris$Sepal.Length))

Upvotes: 6

Darren Bishop
Darren Bishop

Reputation: 2585

library(ggplot2)
qplot(1:nrow(iris), Sepal.Length, data = iris, xlab = "Index")

or

ggplot(data = iris, aes(x = 1:nrow(iris), y = Sepal.Length)) +
    geom_point() +
    labs(x = "Index")

Upvotes: 2

jcarlos
jcarlos

Reputation: 435

require(ggplot2)

x= seq(1,length(iris$Sepal.Length))
Sepal.Length= iris$Sepal.Length

data <- data.frame(x,Sepal.Length)

ggplot(data) + geom_point(aes(x=x,y=Sepal.Length))

enter image description here

Upvotes: 6

Mikko
Mikko

Reputation: 7755

Actually, you are not plotting one variable, but two. X-variable is the order of your data. The answer to what you want based on your example is:

library(ggplot2)
ggplot(iris, aes(y = Sepal.Length, x = seq(1, length(iris$Sepal.Length)))) + geom_point()

The answer to your question would be closer to this:

ggplot(iris, aes(x = Sepal.Length)) + geom_dotplot()

Upvotes: 16

Related Questions