如何在ggplot中绘制一个变量?

ann*_*rey 33 plot r ggplot2

我正在寻找,但仍然无法找到一个非常简单的问题的答案 - 我们怎样才能在R中用ggplot2生成一个变量的简单点图?

使用plot命令这很简单:

plot(iris$Sepal.Length, type='p')
Run Code Online (Sandbox Code Playgroud)

但是当我试图将一个变量传递给qplot并指定geom ="point"时,我收到一个错误"UseMethod中的错误("scale_dimension")".

简单的单变量图

我们怎么能用ggplot2制作这样的情节呢?

Sve*_*ein 53

您可以手动创建索引向量seq_along.

library(ggplot2)

qplot(seq_along(iris$Sepal.Length), iris$Sepal.Length)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Mik*_*kko 13

实际上,你没有绘制一个变量,而是两个.X变量是数据的顺序.根据您的示例,您想要的答案是:

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

你的问题的答案将更接近于此:

ggplot(iris, aes(x = Sepal.Length)) + geom_dotplot()
Run Code Online (Sandbox Code Playgroud)

  • `ggplot(iris,aes(x = Sepal.Length))+ geom_dotplot()`给我一个直方图,而不是一个点图. (2认同)

jca*_*los 5

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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


se7*_*7en 5

使用qplot和不指定data参数的替代方法:

ggplot(mapping=aes(x=seq_along(iris$Sepal.Length), y=iris$Sepal.Length)) +
    geom_point()
Run Code Online (Sandbox Code Playgroud)

要么:

ggplot() +
    geom_point(aes(x=seq_along(iris$Sepal.Length), y=iris$Sepal.Length))
Run Code Online (Sandbox Code Playgroud)