【问题标题】:How to take all the names of colums as y-axis and plot them in the same graph with ggplot?如何将所有列的名称作为 y 轴并将它们与 ggplot 绘制在同一个图中?
【发布时间】:2016-02-28 00:14:29
【问题描述】:

给定这样的数据框:

   V1  V2  V3  V4 ... V25
1  0.3 0.2 0.0 0.0    0.0
2  0.0 0.0 0.1 0.15   0.0
   ...

我想将行名作为 x 轴,将列名(V1:V25)作为 y 轴,并在同一张图中绘制多个区域图。

所以我尝试了:

ggplot(topic_count, aes(x= row.names(topic_count),y = colnames(topic_count),group = colnames(topic_count))) + geom_point()

但得到Error: Aesthetics must be either length 1 or the same as the data (22): x, y 错误。

你知道如何正确地做吗?谢谢。

【问题讨论】:

  • 预期的情节是什么样的?
  • 如果我正确理解您的问题,您会想要将行名(在本例中为数字)添加为列,然后使用tidyr 之类的东西来重塑数据框。使用 dplyr 和 tidyr、topic_count <- topic_count %>% mutate(row_names = row_number()) 和 topic_count_deep <- topic_count %>% gather(cnames, cvals, -row_names)'. You can then plot with ggplot(tc_deep, aes(row_names, cvals, group = cnames)) + geom_point()`的示例
  • @mtoto 图中应该有25 不同的图,row.names 作为 x-asix 和 Vn 作为 y 轴
  • @steveb Error in eval(expr, envir, enclos) : object 'row_names' not found
  • @mtoto 您是否成功运行了第一个命令,topic_count <- topic_count %>% mutate(row_names = row_number())?这将添加“row_names”。

标签: r plot ggplot2


【解决方案1】:

我们需要先融化你的data.frame,然后我们可以使用ggplot 和facet.wrap() 在一个图中生成多个图。

library(reshape2)
library(ggplot2)

df.melted <- melt(as.matrix(df))

ggplot(df.melted, aes(factor(Var1), value)) + 
  geom_point() +
  facet_wrap(~ Var2)

数据

df <- structure(list(V1 = c(0.3, 0), V2 = c(0.2, 0), V3 = c(0, 0.1), 
    V4 = c(0, 0.15)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", "2"))

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多