我使用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);
不知道我做错了什么。Pls help
问题是由 x = Capex
在 geom_text(aes(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-位置。