[英]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.我需要在 X 轴上绘制 AF 的步进曲线,其频率在 Y 轴上由 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'
:我们可以将geom_line
与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)这是一个替代方案(HT 到@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:在常规graphics
库中,您可以执行以下操作:
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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.