简体   繁体   中英

density functions of multiple columns in a dataframe - ggplot

I need some help to produce a graph similar to the one posted here Density plot for numerous variables using ggplot in R

I tried the code mentioned in the post however the result is not good looking在此处输入图像描述

My database looks like this:

    head(df)
 a         b         c         d         e         f         g
1 0.9999994 0.9999994 0.7924445 0.9998647 0.7300587 0.9249790 0.9816021
2 0.9999885 0.9999885 0.6782044 0.9983770 0.6119326 0.9434158 0.9583668
3 1.0000000 1.0000000 0.8709003 0.9999908 0.8181097 0.8939165 0.9942465
4 1.0000000 1.0000000 0.8587627 0.9999847 0.8035536 0.9034016 0.9998198
5 0.9999996 0.9999996 0.8059187 0.9999075 0.7480368 0.9043720 0.9290576
6 0.9999999 0.9999999 0.8532174 0.9999810 0.7971970 0.9059244 0.9983568
dat <- stack(df)
ggplot(dat, aes(x=values, fill=ind)) + geom_density(alpha=0.5)

The values range from 0.6 to 1 I've also tried the approach with pivot_longer but it doesn't have a great look as well .. could anyone help?provide me with suggestions or alternatives? Thanks

If you look at your y axis, you will notice it has very high values. The reason is that the density for column d is extremely high, since its values are all concentrated into a tiny spot. A grouped density plot will calculate the density for each group separately, and the smoothing kernel is scaled according to the range of the data. Since the density of column d has to fit in a range of about 0.001 of the x axis but have an area under its curve of 1, that curve is going to be a very tall sharp spike. Its density therefore "drowns out" the density of all the other groups. If you use coord_cartesian to set the y range, we can see all the other densities much more clearly. Of course, this cuts off the top of the d density since it is three orders of magnitude higher, but this seems like a reasonable compromise.

ggplot(dat, aes(x = values, fill=ind)) + 
  geom_density(alpha = 0.5, position = "identity") + 
  coord_cartesian(ylim = c(0, 30))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM