要向文本添加文本(本例中为地图),需要文本标签和文本坐标。这里是你的数据的方法:
library(ggplot2)
library(fiftystater)
library(tidyverse)
data("fifty_states")
ggplot(data= crimes, aes(map_id = state)) +
geom_map(aes(fill = Assault), color= "black", map = fifty_states) +
expand_limits(x = fifty_states$long, y = fifty_states$lat) +
coord_map() +
geom_text(data = fifty_states %>%
group_by(id) %>%
summarise(lat = mean(c(max(lat), min(lat))),
long = mean(c(max(long), min(long)))) %>%
mutate(state = id) %>%
left_join(crimes, by = "state"), aes(x = long, y = lat, label = Assault))+
scale_x_continuous(breaks = NULL) + scale_y_continuous(breaks = NULL) +
labs(x = "", y = "") + theme(legend.position = "bottom",
panel.background = element_blank())
这里我用了突击号标签和文字的坐标每个州的纬度和经度坐标的最大值和最小值的意思。某些州的坐标可能更好,可以手动添加它们或使用选定的城市坐标。
编辑:用更新的问题:
首先选择犯罪的一年,类型和汇总数据
homicide %>%
filter(Year == 1980 & Crime.Type == "Murder or Manslaughter") %>%
group_by(State) %>%
summarise(n = n()) %>%
mutate(state = tolower(State)) -> homicide_1980
然后剧情:
ggplot(data = homicide_1980, aes(map_id = state)) +
geom_map(aes(fill = n), color= "black", map = fifty_states) +
expand_limits(x = fifty_states$long, y = fifty_states$lat) +
coord_map() +
geom_text(data = fifty_states %>%
group_by(id) %>%
summarise(lat = mean(c(max(lat), min(lat))),
long = mean(c(max(long), min(long)))) %>%
mutate(state = id) %>%
left_join(homicide_1980, by = "state"), aes(x = long, y = lat, label = n))+
scale_x_continuous(breaks = NULL) + scale_y_continuous(breaks = NULL) +
labs(x = "", y = "") + theme(legend.position = "bottom",
panel.background = element_blank())
如果有人想比较所有年份,我建议不用tex牛逼,因为这将是非常混乱:
homicide %>%
filter(Crime.Type == "Murder or Manslaughter") %>%
group_by(State, Year) %>%
summarise(n = n()) %>%
mutate(state = tolower(State)) %>%
ggplot(aes(map_id = state)) +
geom_map(aes(fill = n), color= "black", map = fifty_states) +
expand_limits(x = fifty_states$long, y = fifty_states$lat) +
coord_map() +
scale_x_continuous(breaks = NULL) + scale_y_continuous(breaks = NULL) +
labs(x = "", y = "") + theme(legend.position = "bottom",
panel.background = element_blank())+
facet_wrap(~Year, ncol = 5)
人们可以看到的不是在几年变化太大了。
我相信更翔实的情节是:
homocide %>%
filter(Crime.Type == "Murder or Manslaughter") %>%
group_by(State, Year) %>%
summarise(n = n()) %>%
mutate(state = tolower(State)) %>%
ggplot()+
geom_line(aes(x = Year, y = n))+
facet_wrap(~state, ncol = 6, scales= "free_y")+
theme_bw()
谢谢您的回答。我正在使用来自[link](https://www.kaggle.com/murderaccountability/homicide-reports)的数据集,所以上面的代码不适用于这个数据集。请你可以建议我如何使用上述代码杀人数据集? –
您想从数据集中绘制什么?那么OP中的那个要复杂得多。一年内每个州的谋杀或大屠杀总和?请更新与问题的OP。 – missuse
非常感谢你!这是非常有用的...我可以制作我想要的图表:) –