0
我有一個包含城市,州,年份和謀殺數量在內的多個值的對象。我用dplyr它組由城市和計算超過所有年份的總謀殺的前10個城市是這樣的:R dplyr group,ungroup,top_n和ggplot
MurderNb_reshaped2 %>%
select(city, state, Year, Murders) %>%
group_by(city) %>%
summarise(total = sum(Murders)) %>%
top_n(10, total) %>%
ggplot(aes(x = Year, y = Murders, fill = "red")) +
geom_histogram(stat = "identity") +
facet_wrap(~city)
我想繪製這個只對十大城市,不是'x =一年沒有找到,因爲它已按城市分組。任何人都可以解釋我怎麼能做到這一點?
編輯:這個原始源數據https://interactive.guim.co.uk/2017/feb/09/gva-data/UCR-1985-2015.csv 這裏是我的代碼:
Deaths <- read.csv("UCR-1985-2015.csv", stringsAsFactors = F)
MurderRate <- Deaths[, -c(5:35)]
MurderNb <- Deaths[, -c(36:66)]
colnames(MurderNb) <- gsub("X", "", colnames(MurderNb))
colnames(MurderNb) <- gsub("_raw_murder_num", "", colnames(MurderNb))
MurderNb_reshaped <- melt(MurderNb, id = c("city", "Agency", "state", "state_short"))
colnames(MurderNb_reshaped) <- c("city", "Agency", "state", "state_short", "Year", "Murders")
MurderNb_reshaped2 <- MurderNb_reshaped
MurderNb_reshaped2 %>%
select(city, state, Year, Murders) %>%
group_by(city) %>%
summarise(total = sum(Murders)) %>%
top_n(10, total) %>%
ggplot(aes(x = Year, y = Murders, fill = "red")) +
geom_bar(stat = "identity") +
facet_wrap(~city)
我想你想要一個'geom_bar'而不是直方圖,因爲你有2個維度(年+謀殺)。如果你需要在你的陰謀的一年,你可能還需要包括它作爲一個分組變量 –
謝謝。確定爲geom_bar,但不會包含年份作爲分組變量阻止我正確使用top_n? – Romain
向我們展示您的數據的小樣本,以獲得更好的答案,包括代碼 –