-1

I have a dataframe as shown below:

  ID AC         AF  Type
1 60  1 0.00352113 1
2 48  1 0.00352113 2
3 25  1 0.00352113 1
4 98  1 0.00352113 2
5 24  1 0.00352113 1
6 64  2 0.00704225 1

I need to plot a step curve of AF on X-axis with its frequency on Y-axis colored by TYPE. I managed to have histogram using the below code:

ggplot(data, aes(x = AF,fill=TYPE))+geom_histogram(aes(y = ..count..),bins=40)

However, i need a curve plot as shown below instead of histogram:

enter image description here

Any suggestions to achieve this?

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
chas
  • 1,565
  • 5
  • 26
  • 54

2 Answers2

0

We can use geom_line with stat = 'count':

First I generate some dummy data:

set.seed(123)
df1 <- data.frame(Type = sample(1:3, 100, replace = T),
                  AF = sample(1:10, 100, replace = T, 
                              prob = seq(.8, .2, length.out = 10)))

Then we make the plot:

ggplot(df1, aes(x = AF))+
    geom_line(stat = 'count', aes(group = Type, colour = factor(Type)))

enter image description here

Here's an alternative (HT to @eipi)

set.seed(123)
df1 <- data.frame(Type = sample(1:3, 1000, replace = T),
                  AF = round(rnorm(1000), 3))

ggplot(df1, aes(x = AF))+
    geom_step(stat = 'bin', aes(group = Type, colour = factor(Type)),
              bins = 35)

enter image description here

bouncyball
  • 10,631
  • 19
  • 31
0

In the regular graphics library you can do this:

set.seed(1)
AF<-sample(1:20,1000,replace=TRUE)
set.seed(2)
TYPE<-sample(c(1:2),1000,replace = TRUE)

plot(table(AF[which(TYPE==1)])/length(AF[which(TYPE==1)]),type="l",col="blue",
     ylab="Frequency of AF",xlab="AF")
points(table(AF[which(TYPE==2)])/length(AF[which(TYPE==2)]),type="l")
legend("bottomright",c("Type1","Type2"),lty=1,lwd=3,col=c("blue","black"))

enter image description here

nadizan
  • 1,323
  • 10
  • 23