我的问题与我们在ggplot中添加geom_text()的时间有关,它给了我一个错误。我提到了以下链接,但无法解决我的问题。
访问过的问题:geom_text not working when ggmap and geom_point used
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
如果您选择回答,请简要说明发生此错误的原因。会很感激。
谢谢。
答案 0 :(得分:3)
一个问题是使用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")