具有假设的反指数拟合的geom_smooth

问题描述 投票:0回答:1

采用以下代码,我可以生成一个简单的直方图:

A <- c(rep(0,200),rep(1,1000),rep(2,200),rep(3,100),rep(4,50),rep(5,10))
B <- c(rep("Apple",200),rep("Orange",1000),rep("Pear",200),rep("Grape",100),rep("Banana",50),rep("Nuts",10))

df1 <- data.frame(A,B)


library(ggplot2)
g <- ggplot(df1, aes(A)) + 
  geom_bar() + theme_bw() +
  ylim(0, 1500) 
g

如何添加红色虚线拟合以通过点(A = 1,y = 2000),(2,200),(3,100),(4,50),(5,10),而不会更改y限制?

r ggplot2 curve-fitting exponential
1个回答
0
投票

创建新的数据框:

df2 <- data.frame(A=0:5, B=c(0, 2000, 200, 100, 50, 10))

为了完整起见,我还包括A = 0。现在让我们绘制图形:

ggplot(df1, aes(A)) + 
  geom_bar() + 
  theme_bw() +
  geom_line(data=df2, aes(x=A, y=B, color="red")) + 
  coord_cartesian(ylim = c(0, 1500))

键正在使用coord_cartesian,而不是ylim,它在y轴上重新缩放而不丢失数据。这给你

© www.soinside.com 2019 - 2024. All rights reserved.