【问题标题】:Include facet_wrap in R line plot在 R 线图中包含 facet_wrap
【发布时间】:2021-01-12 13:00:51
【问题描述】:

我有以下代码来绘制折线图:

df %>% pivot_longer(-Client) %>%
  ggplot(aes(x=name,y=value,color=factor(Client),group=factor(Client)))+
  geom_line()+
  xlab('Client')+
  theme_bw()+
  labs(color='Client')

它为我的每个客户绘制一条线,但由于我有太多客户,将所有客户都绘制在一个图中会变得非常混乱,我一直在尝试使用 facet_wrap() 函数将客户分开图表,但无法弄清楚如何做到这一点,所以我在这里......

有一个我的数据样本:

         Client   Model_1      Model_2      Model_3    Model_4      Model_5
            1       10.34        0.22        0.62        0.47         1.96
            2        0.97        0.60        0.04        0.78         0.19
            3        2.01        0.15        0.27        0.49         0.00
            4        0.57        0.94        0.11        0.66         0.00
            5        0.68        0.65        0.26        0.41         0.50
            6        0.55        3.59        0.06        0.01         5.50
            7       10.68        1.08        0.07        0.16         0.20

【问题讨论】:

  • 我可以看看你尝试使用facet_wrap()吗?

标签: r ggplot2 plot


【解决方案1】:

尝试使用这样的模块创建一个超过客户数量的组:

library(ggplot2)
library(dplyr)
library(tidyr)
#Code
df %>% pivot_longer(-Client) %>%
  mutate(Group=ifelse(Client %% 2==0,'G1','G2')) %>%
  ggplot(aes(x=name,y=value,color=factor(Client),group=factor(Client)))+
  geom_line()+
  xlab('Client')+
  theme_bw()+
  labs(color='Client')+
  facet_wrap(.~Group,scales = 'free')

输出:

【讨论】:

  • 如果我想创建 3 个组,我可以在 mutate() 中写一个 if - elseif - else 来做到这一点??
  • @ArturBraga 是的,你可以,但在这种情况下,你应该使用其他选项,如 %in% 和矢量,如 1:34:6 等等!
猜你喜欢
  • 1970-01-01
  • 2020-04-29
  • 2014-06-28
  • 2023-03-02
  • 2018-06-04
  • 1970-01-01
  • 2017-02-26
  • 2020-03-08
  • 1970-01-01
相关资源
最近更新 更多