Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
847 views
in Technique[技术] by (71.8m points)

ggplot2 - Include facet_wrap in R line plot

I have the following code to plot a line graph:

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')

It plots a line for each of my clients, but since i have too many clients, plot all of them in one graph gets pretty messy, I've been tryin to use the facet_wrap() function to divide the clients in separate graphs but couldn't figure out how to do this, so here I am...

There is a sample of my data:

         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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try creating a group over number of customer using module like this:

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')

Output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...