Search code examples
rggplot2density-plot

Cannot generate different colours using qplot for geom=density


I am trying to generate a density plot using qplot for a factor variable. I used the following code

qplot(
    file1$month, 
    geom = "density", 
    main ="Density function of Months", 
    xlab = "Month", 
    col=I(("red")))

which works for coloring all the lines but i need different colors for each line i.e. 12 for 12 months. Error says aesthetics must be equal to data which is 4613. I clearly don't have data of 4613. How to plot different colors for each month?


Solution

  • You'll need a column in file1 which identifies which rows are which colours. Say you generate that column and it's called `plotColor'. Then it's as simple as

    qplot(
        file1$month, 
        geom = "density", 
        main ="Density function of Months", 
        xlab = "Month", 
        colour= file1$plotColour)
    

    Without seeing your data it's hard to give any more advice than that. But I believe you just need a different column which helps distinguish which colours each need to be, and that's what the above solution will give you.