【问题标题】:r create bar plot with two y variablesr 创建带有两个 y 变量的条形图
【发布时间】:2022-08-20 20:23:59
【问题描述】:

我想在 r 中创建一个条形图,它需要两个 y 变量并将它们并排显示,用于一个 x 变量。 下面是我试图绘制的数据的 put 函数的输出

structure(list(SpindleID = structure(1:20, .Label = c(\"3001\", 
\"3002\", \"3003\", \"3004\", \"3005\", \"3006\", \"3007\", \"3008\", \"3009\", 
\"3010\", \"3501\", \"3502\", \"3503\", \"3504\", \"3505\", \"3506\", \"3507\", 
\"3508\", \"3509\", \"3510\"), class = \"factor\"), lowtor = c(39, 83, 
70, 123, 31, 36, 128, 213, 134, 27, 223, 197, 286, 65, 744, 664, 
465, 60, 140, 115), hitor = c(0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 5, 
8, 1, 0, 155, 96, 28, 27, 12, 16)), class = c(\"tbl_df\", \"tbl\", 
\"data.frame\"), row.names = c(NA, -20L))

x 变量是 SpindleID,两个 y 变量是 lower 和 hitor。

谢谢

    标签: r bar-chart


    【解决方案1】:

    首先,使用pivot_longer 制作更长格式的数据框,以便轻松显示您的两个变量,如下所示:

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    df %>%
      pivot_longer(cols = -SpindleID) %>%
      ggplot(aes(x = SpindleID, y = value, fill = name)) +
      geom_bar(stat = "identity", position = "dodge") +
      theme(axis.text.x = element_text(angle = 90))
    

    创建于 2022-08-20,reprex v2.0.2

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 2019-06-01
      • 2021-07-31
      • 2019-01-23
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      相关资源
      最近更新 更多