【问题标题】:Plotting dataframe with ggplot2 in R在 R 中使用 ggplot2 绘制数据框
【发布时间】:2021-02-10 22:54:02
【问题描述】:

假设我有一个名为“df”的数据框

A <- seq(1, 10, 2)
B <- c("apple", "strawberry")

combination <- expand.grid(A, B) 
colnames(combination) <- c("A", "B")
 
df <- cbind(combination)
colnames(df) <- c("A", "B")
df$C <- seq(1, 10, 1)

df

我在这里要做的是用2条线绘制一个图(每条线代表“B”列中的“苹果”和“草莓”),其中x轴是“A”,y轴是“C” ",通过使用 ggplot2.谁能帮我解决这个问题?

【问题讨论】:

    标签: r dataframe ggplot2


    【解决方案1】:

    试试这个。您可以在aes() 中启用选项colorgroup 并设置B 变量。这里使用ggplot2函数的代码:

    library(ggplot2)
    #Data
    A <- seq(1, 10, 2)
    B <- c("apple", "strawberry")
    
    combination <- expand.grid(A, B) 
    colnames(combination) <- c("A", "B")
    
    df <- cbind(combination)
    colnames(df) <- c("A", "B")
    df$C <- seq(1, 10, 1)
    
    df
    #Plot
    ggplot(df,aes(x=A,y=C,color=B,group=B))+
      geom_line()
    

    输出:

    【讨论】:

      猜你喜欢
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 2022-08-13
      相关资源
      最近更新 更多