【问题标题】:Plotting ratios for categorical variables with ggplot使用 ggplot 绘制分类变量的比率
【发布时间】:2021-05-06 08:34:55
【问题描述】:

我的数据如下:

dat <- structure(list(Obstacle = structure(c(4L, 2L, 3L, 1L), .Label = c("Major Obstacle", 
"Minor Obstacle", "Moderate Obstacle", "No Obstacle", "Total"
), class = "factor"), `Crime = 1` = c(0.842430787355193, 0.724891824185835, 
0.692470837751856, 0.673805601317957), `Crime = 2` = c(0.157569212644807, 
0.275108175814165, 0.307529162248144, 0.326194398682043)), row.names = c(NA, 
4L), class = "data.frame")

            Obstacle Crime = 1 Crime = 2
1       No Obstacle 0.8424308 0.1575692
2    Minor Obstacle 0.7248918 0.2751082
3 Moderate Obstacle 0.6924708 0.3075292
4    Major Obstacle 0.6738056 0.3261944

我想将 y 轴设为比率,x 轴有序数障碍值的值,其中Crime = 1 是一条线,Crime = 2 是一条线。

我尝试过:

graph <- melt(graph, id="Obstacle")
library(ggplot2)
ggplot(data=graph,
       aes(x=Obstacle, y=value, colour=variable)) +
       geom_line()

但这会导致一个空的情节,以及 ggplot 问题:

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    ggplot 信息明确,添加 group 到 aes:

    graph <- reshape2::melt(dat, id = "Obstacle")
    
    ggplot(data = graph,
           aes(x = Obstacle, y = value, colour = variable, group = variable)) +
      geom_line()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2017-08-25
      • 2015-05-25
      • 2016-01-06
      • 2018-08-30
      • 2018-03-15
      相关资源
      最近更新 更多