我试图在地图上绘制垂直条形图。我在线浏览了一些例子,但不知怎的。
我的数据目前采用以下格式:
University| Count | Category | lat | long
以下是我尝试执行的代码:
library(ggplot2)
library(ggmap)
library(ggsubplot)
df1 <- data.frame(
University = c(rep("University1", 4), rep("University2", 4), rep("University3", 4),
rep("University4", 4)),
Count = sample(1:10, 16, replace = T),
Category = rep(c("A", "B", "C", "D")),
lat = c(rep(10.902469, 4), rep(17.921959, 4), rep(18.606910, 4), rep(13.202366, 4)),
long = c(rep(76.90020, 4), rep(83.42510, 4), rep(73.87501, 4), rep(77.62340, 4))
)
india <- get_map("India", zoom = 5)
p <- ggmap(india)
p + geom_subplot(data = df1, mapping=aes(x = long, y = lat, group = University,
subplot= geom_bar(aes(x = Category, y = Count, color = Category, stat = "identity"))))
当我运行上面的代码时,我收到以下错误:
Error in get(x, envir = this, inherits = inh)(this, ...) :
could not find function "%:::%"
答案 0 :(得分:10)
您还应该使用mapproj
包。使用以下代码:
ggmap(india) +
geom_subplot(data = df1, aes(x = long, y = lat, group = University,
subplot = geom_bar(aes(x = Category, y = Count,
fill = Category, stat = "identity"))))
我得到了以下结果:
正如问题评论中所述:此解决方案适用于R 2.15.3但由于某些原因不适用于R 3.0.2
更新16 januari 2014:当您将ggsubplot软件包更新到最新版本时,此解决方案现在也适用于R 3.0.2
更新2014年8月2日:在包裹作者(Garret Grolemund)关于@jazzuro提到的issue(文本格式化我的)的答案之下:
不幸的是,
ggsubplot
不是很稳定。ggplot2
不是 设计为可扩展或递归,所以ggsubplot
之间的api 并且ggplot2
被非常陪审团操纵。我认为熵会断言 随着R继续更新。未来的开发计划是将ggsubplot实现为内置版 在哈德利的新包
ggvis
的一部分。这将是更多 可维护而不是ggsubplot
+ggplot2
配对。几个月后我无法调试ggsubplot,但是我 很乐意接受github上的拉取请求。
2016年12月23日更新:ggsubplot
- 套餐不再受到积极维护,且为archived on CRAN:
包'ggsubplot'已从CRAN存储库中删除。
可以从存档中获取以前可用的版本。
按照维护者的要求在2016-01-11进行存档
答案 1 :(得分:0)
实际上,我们可以使用geom_errorbar()
在地图中实际添加一个条形图。只要将geom_errorbar()
的x和y设置为经度和纬度即可; ymin和ymax是您数据的统计信息。
library(tidyverse)
plant_data <- read.csv("DV.csv")
colnames(plant_data) <- c("name", "lat", "lon", "p", "t", "hmi")
head(plant_data)
# name lat lon p t hmi
# 1 Dodonaea viscosa subsp. viscosa -17.3000 145.9667 4084 24.1 8.905719509
# 2 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
# 3 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
# 4 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
# 5 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
# 6 Dodonaea viscosa subsp. viscosa -18.0833 146.0000 2562 24.0 13.18851823
aus <- map_data('world', region = "(Australia)|(Indonesia)|(Papua New Guinea)")
ggplot() +
geom_polygon(data = aus, aes(x = long, y = lat, group = group),
fill = "gray80") +
geom_point(data = plant_data, aes(x = lon, y = lat), color = '#00CC00') +
coord_map(xlim = c(110, 160), ylim = c(-45, -5)) +
ggtitle("植物分布") +
theme(plot.title = element_text(hjust = 0.5)) +
geom_errorbar(data = plant_data[c(50, 99), ],
aes(x = lon,ymin=lat-3,ymax=lat+1),
color='blue', size = 3, width=0)
这部分非常聪明:
geom_errorbar(data = plant_data[c(50, 99), ],
aes(x = lon,ymin=lat-3,ymax=lat+1),
color='blue', size = 3, width=0)
这太神奇了!