【问题标题】:Using ggplot2 to create a plot with more than 2 variables使用 ggplot2 创建具有 2 个以上变量的绘图
【发布时间】:2016-05-04 18:59:18
【问题描述】:

我正在研究一个包含多个变量的数据集,如下面的示例所示;(实际数据集包含:84 obs。24 个变量)。我想创建一个包含所有变量的图,而不是为每个变量创建一个图。

Fruit    Vitamin A(mg) Vitamin C(mg) Calcium(mg)
Pear         61            8             11
Apple        10            2             3
Cherry       35            10            11
Fig          5             2             67

我已经尝试了下面的代码,这是其中一个论坛中建议的代码的修改版本;

library(ggplot2)
g<- ggplot(FR, aes(Fruit)
g + geom_point() + facet_grid(. ~ FR[2:26,])

我得到错误;

错误:出现意外符号:“g

对于表示数据集的替代方案,我愿意接受任何更好的建议。

【问题讨论】:

  • geom_point() 需要一个 y 轴和一个 x 轴。您只指定了一个 x 轴。您希望其他列成为 Y 吗?

标签: r plot ggplot2


【解决方案1】:

这个怎么样:

为此,您需要使用 gather{tidyr} 重塑数据集。这是一个关于如何执行此操作的可重现示例:

# load libraries
  library(ggplot2)
  library(ggthemes)
  library(tidyr)
  library(googleVis)

# get data for a reproducible example
  data("Fruits")
  colnames(Fruits)[4] <- "Vitamin A(mg)"
  colnames(Fruits)[5] <- "Vitamin C(mg)"
  colnames(Fruits)[6] <- "Calcium(mg)"
  Fruits <- Fruits[ c("Fruit","Vitamin A (mg)" , "Vitamin C (mg)", "Calcium (mg)")]

# reshape the dataset
  df <- gather(data=Fruits, key=Fruit)
  colnames(df)[2] <- "vitamin"


# Plot !
  ggplot(data=df) +
    geom_point(aes(x=vitamin, y=value , color=vitamin)) +
    facet_grid(Fruit~., scale="free_x") +
    theme_minimal() 

【讨论】:

  • 这与我想要的最接近,我将水果作为我的 x 值。虽然该图在小数据集上看起来很棒,但在像我这样大的数据集上都聚集在一起并且模糊不清,我可能需要对变量进行分类。谢谢,这很有帮助。
【解决方案2】:

我相信您缺少右括号。变化:

g<- ggplot(FR, aes(Fruit)

g<- ggplot(FR, aes(Fruit))

根据我的经验,“意外符号”错误通常意味着您忘记关闭括号或大括号。

【讨论】:

  • 我收到错误:layout_base 中的错误(数据,cols,drop = drop):至少一层必须包含用于构面的所有变量
【解决方案3】:

您没有足够地指定轴。

ggplot(FR, aes(x = Fruit, y = Vitamin A(mg), 
    shape = as.factor(Fruit), 
    color = as.factor(Fruit))) + 
    geom_point() +
    geom_point(aes(x = Fruit, y = Vitamin C(mg))) +
    geom_point(aes(x = Fruit, y = Calcium(mg)))

这是你想要的吗?

【讨论】:

  • 适用于具有相同单位的变量,但不适用于我的数据中有卡路里(千卡)的情况。抱歉,我之前忘了提这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-30
相关资源
最近更新 更多