[英]Strange behaviour when adding geom_text() or annotate() to coord_polar plot in ggplot2
[英]issue when adding geom_text in ggplot2 when plotting ggmap
我的問題與我們在ggplot中添加geom_text()的時間有關,它給了我一個錯誤。 我提到了下面的鏈接,但無法解決我的問題。
訪問過的問題: 使用ggmap和geom_point時geom_text無法正常工作
library(ggplot2)
library(maps)
library(Hmisc)
library(stringi)
data(state)
states <- map_data("state")
colnames(states)[5] <- "State"
states$State <- stri_trans_totitle(states$State)
df <- data.frame(state.x77,
State = state.name,
Abbrev = state.abb,
Region = state.region,
Division = state.division
)
df2 <- merge(states,df,by="State")
df2 <- df2[order(df2$order),]
mid_range <- function(x) mean(range(x,na.rm=TRUE))
centres <- ddply(df2, .(Abbrev),
colwise(mid_range,.(lat,long,Population)))
gg <- function(Cols) {
df2$Cols <- df2[,Cols]
ggplot(df2, aes(long,lat,fill=Cols))+
geom_polygon(aes(group=group))
#+ geom_text(aes(x=long,y=lat,label=Abbrev),data = centres,size=4)
}
使用上面的代碼,我得到以下輸出:
gg("Population")
然后,如果我取消注釋geom_text()函數並重新運行代碼,我會收到以下錯誤:
Error in +geom_text(aes(x = long, y = lat, label = Abbrev), data = centres, :
invalid argument to unary operator
如果您選擇回答,請簡要說明發生此錯誤的原因。 會很感激。
謝謝。
一個問題是使用geom_text
行開頭的+號。 將+號移動到上一行的末尾。 但仍然會產生錯誤。 我認為問題在於兩個數據框中的常見變量名稱。 將data
和aes
命令從ggplot
到geom_polygon
。
library(ggplot2)
library(plyr)
library(maps)
library(Hmisc)
library(stringi)
data(state)
states <- map_data("state")
colnames(states)[5] <- "State"
states$State <- stri_trans_totitle(states$State)
df <- data.frame(state.x77,
State = state.name,
Abbrev = state.abb,
Region = state.region,
Division = state.division
)
df2 <- merge(states,df,by="State")
df2 <- df2[order(df2$order),]
mid_range <- function(x) mean(range(x,na.rm=TRUE))
centres <- ddply(df2, .(Abbrev),
colwise(mid_range,.(lat,long,Population)))
gg <- function(Cols) {
df2$Cols <- df2[,Cols]
ggplot()+ # Changes made here
geom_polygon(data = df2, aes(long,lat,fill=Cols,group=group)) + # and here.
geom_text(aes(x=long,y=lat,label=Abbrev), data = centres, size=4)
}
gg("Population")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.