简体   繁体   中英

How to plot frequency as step curve in R

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:

在此处输入图片说明

Any suggestions to achieve this?

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)))

在此处输入图片说明

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)

在此处输入图片说明

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"))

在此处输入图片说明

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