【问题标题】:How to get data to show as a barplot?如何让数据显示为条形图?
【发布时间】:2015-03-14 17:58:33
【问题描述】:

这是我的数据。我正在尝试使用 R 将数据表示为条形图。

row.names,we,dna,dftd,ee,ebola,onc,smt
Author,4.75,7.7222,4.0698,6.9796,6.9545,8.3809,4.6391
Journal,0.45,0.4444,0.7442,0.6327,0.5151,0.5,0.5325
Year,0.35,0.5278,0.5349,0.3469,0.5,0.1548,0.1243

we,dna,dftd,ee,ebola,onc,smt 都是文章名称。 4.75:4.6391 是每篇文章中的作者差异。 .45:.5325 是每篇文章的期刊差异。 .35:.1243 是每篇文章中的年份差异。

最终目标是创建一个在 y 轴上具有方差且在 x 轴上具有文章标题的条形图。每个文章标题上方应有 3 个栏,分别代表作者、期刊和年份。

我不知道如何让这些数据在 R 中显示为条形图。

我加载了它:

bp=read.csv(file.choose(),header=T)

如果我从这里输入 barplot(bp) 它告诉我高度必须是向量或矩阵,我所知道的向量是你可以用c(...) 创建它们。

我到处搜索并尝试了几天才在这里问。

我知道这是一个简单的命令,但我就是不知道我做错了什么。

【问题讨论】:

    标签: r plot bar-chart


    【解决方案1】:

    您需要在向量或矩阵中输入 barplot() 高度,正如您在错误消息中所指出的那样。

    我假设您现在将数据保存在 data.frame() 中。

    dat <- read.csv(text = "row.names,we,dna,dftd,ee,ebola,onc,smt
    Author,4.75,7.7222,4.0698,6.9796,6.9545,8.3809,4.6391
    Journal,0.45,0.4444,0.7442,0.6327,0.5151,0.5,0.5325
    Year,0.35,0.5278,0.5349,0.3469,0.5,0.1548,0.1243")
    
    # make data.frame into a matrix of numbers and get rid of the row.names
    dat_matrix <- data.matrix(dat[, -1])
    
    # make a barplot of the variances for each article
    barplot(dat_matrix, beside = TRUE)
    

    上面创建了这个图:

    如果您愿意,您也可以使用 ggplot2 包来完成此操作。 在绘图之前,您需要将数据从宽调整为长,这可以使用 reshape2 来完成。

    # reshape data from wide to long and rename variables
    library(reshape2)
    dat_long <- melt(dat, id.vars = "row.names",
                  variable.name = "article_name",
                  value.name = "variance_value")
    
    library(ggplot2)
    p <- ggplot(data = dat_long, aes(x = article_name, y = variance_value, fill = row.names)) 
    p <- p + geom_bar(stat = "identity", position = "dodge")
    p
    

    ggplot2 版本:

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多