【问题标题】:Plotting DataFrame in R ggplot shows an error for aesthetics在 R ggplot 中绘制 DataFrame 显示美学错误
【发布时间】:2021-05-25 16:38:14
【问题描述】:

我有以下数据框:

数据框(habSolyc05g052120.2):

Shab_ovul1 Shab_poll1 Shab_poll2 Shab_styl1  Shab_styl2 Shab_styl3

         0  0.6145496  0.3681263 0.04324981 0.002682159 0.04056765

我只是想做一个简单的点图,甚至在添加其他物种的基因表达水平之前,以便弄清楚。我正在尝试以下单独的代码:

ggplot(habSolyc05g052120.2, aes(x = habSolyc05g052120.2[,1:6],
y = habSolyc05g052120.2[1,])) +
 geom_point()

ggplot(habSolyc05g052120.2) + 
geom_point(aes(x = (colnames(habSolyc05g052120.2)),
y = habSolyc05g052120.2[1,], 
fill = colnames(habSolyc05g052120.2)))
ggplot(habSolyc05g052120.2) +
geom_point(aes(x = (colnames(habSolyc05g052120.2)),
y = habSolyc05g052120.2[1,]))
ggplot(habSolyc05g052120.2[1,]) +
geom_point(aes(x = (colnames(habSolyc05g052120.2)),
y = habSolyc05g052120.2[1,], fill = colnames(habSolyc05g052120.2)))

它们都不起作用,每个都输出一些版本的错误:

Error: Aesthetics must be either length 1 or the same as the data (1): x and y

不知道如何为 data.frame 类型的对象自动选择比例。默认为连续。

【问题讨论】:

  • 您是否尝试将data.frame 中的6 列用于x?然后对于y,您只选择整个第一行?请记住,data.frame 中的每个变量一列,每个观察值一行。然后您可以为x 设置一个变量,为y 设置一个变量。
  • 制作一个长格式的数据框。有几个选项,但 tidyr::pivot_longer() 效果很好

标签: r ggplot2


【解决方案1】:

为了美观,在ggplot 中,您不应该索引您的数据框,它会自行获取所有变量。
由于您的问题格式不正确,我不知道您的数据框结构,但可能是您想要的:

library(ggplot2)
library(tidyverse)

# creating a dataframe similar to yours
habSolyc05g052129.2 <- data.frame(
  Shab_ovul1 = 0,
  Shab_poll1 = 0.6145496,
  Shab_poll2 = 0.368,
  Shab_styl1 = 0.043,
  Shab_styl2 = 0.0026,
  Shab_styl3 = 0.0405
)

# reshaping daraframe to ling format
habSolyc05g052129.2 <- habSolyc05g052129.2 %>% 
  pivot_longer(cols = 1:6, names_to = "Variables", values_to = "Values")

# main plot
ggplot(habSolyc05g052129.2, aes(x = Variables, y = Values)) +
  geom_point()

输出:

【讨论】:

  • 非常感谢,做得很完美。将来我应该如何更好地呈现我的数据?
  • @tbiewerh,SO 的常用格式是dput 格式。你可以阅读它的文档和教程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
相关资源
最近更新 更多