r - 绘制ggmap时在ggplot2中添加geom_text时出现问题

标签 r ggplot2 unary-operator

我的问题与我们在 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")

enter image description here

然后,如果我取消注释 geom_text() 函数并重新运行代码,则会收到以下错误:

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

如果您选择回答,请简要解释为什么会出现此错误。将不胜感激。

谢谢。

最佳答案

一个问题与 geom_text 行开头的 + 号有关。将 + 号移动到上一行的末尾。但仍然会产生错误。我认为问题在于两个数据框中的公共(public)变量名称。将 dataaes 命令从 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

关于r - 绘制ggmap时在ggplot2中添加geom_text时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23003312/

相关文章:

r - 在ggplot2中向x轴添加文本

r - 如何访问已传递给 ggplot() 的数据框?

r - 绘制带有数据表的堆积条形图

c - 一元 + 运算符是否进行类型转换?

r - 使用 R 估算 NetCDF 数据的每月气候学

r - 从列表中提取第一个值

r - 有没有办法使用R来打破图表轴并打破线性回归线?

r - ggplot2:如何在图例中创建虚线?

c++ - 在调用 std::numeric_limits<unsigned char> 成员之前,一元 "+"的目的是什么?

javascript - 为什么这个一元函数在另一个 javascript 函数中?