代码之家  ›  专栏  ›  技术社区  ›  cigarettes_after_text

为什么ggplot没有正确连接点?复制

  •  0
  • cigarettes_after_text  · 技术社区  · 3 年前

    我如何创建 折线图 对于ggplot 2,其中x变量是分类变量或因子,y变量是数字变量,组变量是分类的?如上所述,我只尝试了+geom_point()和变量,它有效,但+geom_line()无效。

    我已经审阅了以下帖子: Creating line graph using categorical data , ggplot2 bar plot with two categorical variables No line in plot chart despite + geom_line() ,但他们都没有回答我的问题。

    在我进入代码和示例之前,(1)是的,我绝对必须将x变量和组变量作为字符或因子,(2)不,我不想要条形图,也不想要geom_point()。

    以下示例提供了使用因变量的不同变化进行的三个不同示例回归的多个自变量的系数。虽然下面的代码显示了我解决的问题(即创建一个名为“test”的int变量来代替包含回归中自变量名称的chr变量),但我需要能够保留自变量的chr名称。

    以下是我所拥有的:

    library(dplyr)
    library(ggplot2)
    library(plotly)
    library(tidyr)
    
    var_names <- c("ST1", "ST2", "ST3", 
                   "EFI1", "EFI2", "EFI3", "EFI4", 
                   "EFI5", "EFI6")
    
    ####Dataset1####
    reg <- c(26441.84, 20516.03, 12936.79, 17793.22, 18837.48, 15704.31, 17611.14, 17360.59, 14836.34)
    r_adj <- c(30473.17, 35221.43, 29875.98, 30267.31, 29765.9, 30322.86, 31535.66, 30955.29, 29828.3)
    a_adj <- c(19588.63, 31163.79, 22498.53, 27713.72, 25703.89, 28565.34, 29853.22, 29088.25, 25213.02)
    
    df1 <- data.frame(var_names, reg, r_adj, a_adj, stringsAsFactors = FALSE)
    df1$test <- c(1:9)
    
    df2 <- gather(df1, key = "series_type", value = "value", c(2:4))
    
    fig7 <- ggplot(df2, aes(x = test, y = value, color = series_type)) + geom_line() + geom_point()
    fig7
    

    最终,我想要一个看起来像下图的东西,但用自变量名称代替“测试”变量。

    Example Plot

    0 回复  |  直到 5 年前
        1
  •  9
  •   lroha    5 年前

    您可以转换 var_names 转换为一个因子,并按出现的顺序设置级别(否则将按字母数字进行分配,x轴将无序排列)。然后添加 series_type 到绘图中的组参数。

    df2 <- gather(df1, key = "series_type", value = "value", c(2:4)) %>%
      mutate(var_names = factor(var_names, levels = unique(var_names)))
    
    ggplot(df2, aes(x = var_names, y = value, color = series_type, group = series_type)) + geom_line() + geom_point()
    

    enter image description here