When adding geom_text to ggplot2 when building ggmap

my problem is when we add geom_text () to our ggplot, it gives me an error. I referenced the links below, but could not understand my problem.

Questions that were visited: geom_text does not work when using ggmap and geom_point

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)
}

With the above code, I get the following output:

gg("Population")

enter image description here

Then, if I uncomment the geom_text () function and re-run the code, I get the following error:

Error in +geom_text(aes(x = long, y = lat, label = Abbrev), data = centres,  : 
invalid argument to unary operator

If you decide to answer, leave a brief explanation of why this error occurs. Thank him.

Thank.

+4
source share
1 answer

+ 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")

enter image description here

+3

Source: https://habr.com/ru/post/1536040/


All Articles