我的问题与我们在 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
如果您选择回答,请简要解释为什么会出现此错误。将不胜感激。
谢谢。
最佳答案
一个问题与 geom_text
行开头的 + 号有关。将 + 号移动到上一行的末尾。但仍然会产生错误。我认为问题在于两个数据框中的公共(public)变量名称。将 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")
关于r - 绘制ggmap时在ggplot2中添加geom_text时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23003312/