【问题标题】:How do I create line plots with multiple count variables in ggplot2?如何在 ggplot2 中创建具有多个计数变量的线图?
【发布时间】:2021-05-03 20:22:29
【问题描述】:

我正在创建一个包含多个非离散计数变量的图。我有三个按月绘制的独立计数变量。我有一个解决方案,但我觉得它可能不是最简洁和有限的。

df_test <- structure(list(total = c(323L, 263L, 171L, 
12L, 6L, 59L, 253L, 187L, 161L, 160L, 136L, 185L, 6L), month_name = structure(c(1L, 
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, NA), .Label = c("Jan", 
"Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", 
"Nov", "Dec"), class = "factor"), neg = c(268L, 
231L, 146L, 10L, 6L, 55L, 237L, 177L, 140L, 131L, 107L, 155L, 
3L), pos = c(55, 32, 25, 2, 0, 4, 16, 10, 21, 
29, 29, 30, 1)), row.names = c(NA, -13L), class = c("tbl_df", 
"tbl", "data.frame"))

ggplot() +
  geom_line(data = na.omit(df_test), aes(x=month_name, y=total), colour = "blue", group=1) +
  geom_line(data = na.omit(df_test), aes(x=month_name, y=neg), colour = "black", group=1) +
  geom_line(data = na.omit(df_test), aes(x=month_name, y=pos), colour = "red", group=1) +
  xlab("Month") +
  ylab("Count")

所以这就是我想要的,但我认为由于数据都在同一个数据框中,可能有一种更简洁的方式,然后我可以编辑图例并添加点。

谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    只需重塑您的数据:

    m <- reshape2::melt(df_test,id.vars="month_name")
    
    ggplot(na.omit(m),aes(x=month_name,y=value,group=variable,col=variable)) +
      geom_line()
    

    从这里您可以根据需要自定义情节

    【讨论】:

      【解决方案2】:

      试试这个,这应该可以让你编辑图例名称等:

      df_test2<-pivot_longer(df_test, cols = c("neg", "pos", "total")) %>%
        ungroup()
      df_test2 %>%
        ggplot(.) + geom_point(aes(x=month_name, y = value, color = name)) +
        geom_line(aes(x=as.numeric(month_name), y = value, color = name)) +theme_classic()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-09
        • 2013-08-31
        • 1970-01-01
        • 1970-01-01
        • 2023-02-13
        • 2018-07-02
        • 1970-01-01
        相关资源
        最近更新 更多