r-Geom_text标签的位置不正确



图形

我使用geom_text在条形图上添加标签,但它们不在正确的位置(如图所示(。这是我的代码:

df<-data.frame(Project=datafram$Project,Capex=datafram$Capex,width=datafram$Capex, Emissions=datafram$Emissions)
df$w <- cumsum(df$width) #cumulative sums.
df$wm <- df$w - df$width
df$Emissions<- with(df, wm + (w - wm)/2)
p  <- ggplot(df, aes(ymin = 0))
p1 <- p + geom_rect(aes(xmin = wm, xmax = w, ymax = Emissions, fill = Project))
p2<-p1 + geom_text(aes(x = Capex, y = Emissions, label = Project), size=4, nudge_x = c(0.22,-0.22) ) 
p3<-p2+labs(title = "Abatement Curve", x = "Capex", y = "Capital Efficiency")
g=p3;
p = ggplotly(g);

不确定我做错了什么。请帮助

问题是由geom_text(aes(x = Capex, ...))中的x = Capex引起的。您可能希望ggplot在geom_rects的顶部中间绘制文本-可以这样做:

df <- data.frame(Project = c("one", "two", "three", "four", "five", "six"), Capex = c(4000, 4000, 1000,2000,10000,1000))
df$w <- cumsum(df$Capex)
df$wm <- df$w - df$Capex
df$Emissions<- with(df, wm + (w - wm)/2)
p <- ggplot(df) +
geom_rect(aes(ymin = 0, xmin = wm, xmax = w, ymax = Emissions, fill = Project)) +
geom_text(aes(x = wm + Capex/2, y = Emissions, label = Project), size = 4, nudge_y = 180) +
labs(title = "Abatement Curve", x = "Capex", y = "Capital Efficiency")

使用x = wm + Capex/2,我通过每个geom_rect的水平中心作为文本的x位置。

最新更新