JediJesus
JediJesus

Reputation: 329

Plot multiple histograms based on dataframe in R

I have a dataframe that is like this:

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

And i need to plot a histogram for each of this clients(one histogram per line). I've tried to use ggplot2 with cowplot, but didn't worked out very well(I'm new to R), so if anyone could help me i would be thankfull!

Upvotes: 1

Views: 592

Answers (1)

Duck
Duck

Reputation: 39595

Try this:

library(dplyr)
library(tidyr)
library(ggplot2)
#Code
df %>%
  pivot_longer(-Client) %>%
  ggplot(aes(x=name,y=value))+
  geom_bar(stat = 'identity',aes(fill=factor(Client)))+
  facet_wrap(.~Client,scales = 'free')

Output:

enter image description here

In this case you would need a bar plot. Or this for histogram:

#Code 2
df %>%
  pivot_longer(-Client) %>%
  ggplot(aes(x=value))+
  geom_histogram(aes(fill=factor(Client)))+
  facet_wrap(.~Client,scales = 'free')

Output:

enter image description here

Some data used:

#Data
df <- structure(list(Client = 1:7, Model_1 = c(10.34, 0.97, 2.01, 0.57, 
0.68, 0.55, 10.68), Model_2 = c(0.22, 0.6, 0.15, 0.94, 0.65, 
3.59, 1.08), Model_3 = c(0.62, 0.04, 0.27, 0.11, 0.26, 0.06, 
0.07), Model_4 = c(0.47, 0.78, 0.49, 0.66, 0.41, 0.01, 0.16), 
    Model_5 = c(1.96, 0.19, 0, 0, 0.5, 5.5, 0.2)), class = "data.frame", row.names = c(NA, 
-7L))

Upvotes: 1

Related Questions