Reputation: 1238
How is it possible to create a clear density/distribution plot of a dataframe of many variables?
Here is the input:
structure(list(b1_previous = c(0.26981640312419, 0.302252978236613,
0.27519244423907, 0.278573602172958), b2_previous = c(0.165541492443112,
0.162543532408399, 0.150484069110868, 0.212810080358854), b3_previous = c(0.698096408083222,
0.625412783031095, 0.699099484936941, 0.610794910230257), b4_previous = c(0.156164414439798,
0.189265950612553, 0.151656203861282, 0.211930979296043), b5_previous = c(0.384820854982136,
0.364443743167243, 0.352744936715994, 0.397252245652394), b1_next = c(0.290892287578753,
0.279948606399405, 0.262591995672118, 0.327138300630022), b2_next = c(0.170072244074521,
0.190821283262141, 0.136632592108377, 0.185400160041476), b3_next = c(0.637122860008791,
0.595805110056691, 0.713976579846045, 0.594306130039334), b4_next = c(0.154789410213351,
0.185512865305938, 0.136271935262096, 0.18347290001916), b5_next = c(0.359935532588727,
0.391256325582968, 0.352913994612688, 0.312475345723399), before = c(2L,
1L, 2L, 1L), after = c(2L, 1L, 2L, 1L)), row.names = c(NA, -4L
), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x00000000003d1ef0>)
Upvotes: 1
Views: 72
Reputation: 6227
You can use facet_wrap
in ggplot2 to plot different distributions on the same figure:
a = structure(list(b1_previous = c(0.26981640312419, 0.302252978236613,
0.27519244423907, 0.278573602172958), b2_previous = c(0.165541492443112,
0.162543532408399, 0.150484069110868, 0.212810080358854), b3_previous = c(0.698096408083222,
0.625412783031095, 0.699099484936941, 0.610794910230257), b4_previous = c(0.156164414439798,
0.189265950612553, 0.151656203861282, 0.211930979296043), b5_previous = c(0.384820854982136,
0.364443743167243, 0.352744936715994, 0.397252245652394), b1_next = c(0.290892287578753,
0.279948606399405, 0.262591995672118, 0.327138300630022), b2_next = c(0.170072244074521,
0.190821283262141, 0.136632592108377, 0.185400160041476), b3_next = c(0.637122860008791,
0.595805110056691, 0.713976579846045, 0.594306130039334), b4_next = c(0.154789410213351,
0.185512865305938, 0.136271935262096, 0.18347290001916), b5_next = c(0.359935532588727,
0.391256325582968, 0.352913994612688, 0.312475345723399), before = c(2L,
1L, 2L, 1L), after = c(2L, 1L, 2L, 1L)), row.names = c(NA, -4L
), class = c("data.table", "data.frame"))
a %>%
dplyr::select(-before, -after) %>%
tidyr::pivot_longer(everything()) %>%
ggplot(aes(y=value)) + geom_density() + coord_flip() + facet_wrap(~name)
Or, if you want them on the same panel:
a %>%
dplyr::select(-before, -after) %>%
tidyr::pivot_longer(everything()) %>%
ggplot(aes(y=value, fill=name)) + geom_density(alpha=0.3) + coord_flip()
Upvotes: 4