【问题标题】:Formatting data frame to allow for dodged bar plotting格式化数据框以允许进行闪避的条形图
【发布时间】:2021-01-15 14:23:03
【问题描述】:

下午好,

我刚刚问了一个非常相似的问题,但我想我可能用错了,因为问题已经结束,我被指向一个对我没有帮助的答案(它向我展示了如何绘制,而不是如何格式化绘制前的数据)。

我有以下数据:

structure(list(cluster = c(1, 2), age = c(0.67, 0.39), resting_bps = c(0.42, 
0.29), cholesterol = c(0.3, 0.26), max_bps = c(0.51, 0.7)), class = "data.frame", row.names = c(NA, 
-2L))

我希望能够对这些数据进行格式化,这样我就可以为两个相邻的不同集群绘制一个带有不同生物医学值(静息 BPS、胆固醇等)的闪避条形图,如图所示我已经包括在下面了。

我如何操作这个数据框,以便我可以使用以下代码的迭代来为我的特定数据框创建上面的图?

要使用的代码示例:

ggplot(df, aes(x= blank, y=blank, fill = blank)) +
  geom_bar(stat = "identity", position = position_dodge2(preserve = "single")) +
  scale_fill_brewer(palette = "Paired")

请不要通过将我指向显示如何绘制闪避条形图的代码来提前结束此问题。我的问题的重点是询问有经验的 R 程序员如何操作数据框,以便 'ggplot()' 函数适用于我的数据。

【问题讨论】:

    标签: r dataframe data-manipulation


    【解决方案1】:

    试试这个。 ggplot2 中的关键总是将数据整形为长。您可以使用tidyverse 函数来完成此操作,然后绘制绘图:

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    #Code
    df %>%
      pivot_longer(-c(1:2)) %>%
      ggplot(aes(x=name,y=value,fill=factor(cluster)))+
      geom_bar(stat = 'identity',position = position_dodge(0.9))
    

    输出:

    【讨论】:

      【解决方案2】:
      library(tidyverse)
      df<-pivot_longer(df,-1)
      ggplot(df, aes(x= name, y=value, fill = as.character(cluster))) +
       geom_bar(stat = "identity", position = position_dodge2(preserve = "single")) +
       scale_fill_brewer(palette = "Paired")
      

      【讨论】:

        猜你喜欢
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        • 2011-12-12
        • 2016-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多