سؤال

my issue is related to when we add the geom_text() in our ggplot, it gives me an error. I referred to the below links but wasn't able to figure my problem out.

Questions visited: 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)
}

With the above code, I get the following output:

gg("Population")

enter image description here

Then if I uncomment the geom_text() function and rerun 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

Should you choose to answer, do leave a brief explanation as to why this error happens. Would appreciate it.

Thank you.

هل كانت مفيدة؟

المحلول

One problem is to do with the + sign at the beginning of the line with geom_text. Move the + sign to the end of the previous line. But an error is still generated. I think the problem lies with common variable names in the two data frames. Move the data and aes commands out of ggplot into 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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top