要向文本添加文本(本例中爲地圖),需要文本標籤和文本座標。這裏是你的數據的方法:
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
非常感謝你!這是非常有用的...我可以製作我想要的圖表:) –