我正在使用以下代码,但我没有获得变量“Group”或“Group2”的各州密度图,而是获得了包含各种奇怪角度和三角形的美国地图......
我正在使用以下代码,但我没有获得变量“Group”或“Group2”的各州密度图,而是获得了美国地图,其中嵌入了各种跨越州界的奇怪角度和三角形。
library(tidyverse)
theme_set(theme_bw(base_size = 16))
install.packages("foreign")
library("foreign")
data1 <- read.spss("C:/afp/density2.sav", to.data.frame = TRUE)
head(data1)
state_initial states Group Group2 Sum2023
1 AL alabama 2.1 1 3
2 AK alaska 0.0 0 0
3 AZ arizona 1.0 3 6
4 AR arkansas 4.0 3 2
5 CA california 1.0 20 15
6 CO colorado 6.0 4 5
us_states <- map_data("state")
us_states %>%
left_join(data1, by = c("region" = "states")) %>%
ggplot(aes(x = long, y = lat, group = Group, fill = Group)) +
geom_polygon(color = "gray90", size = 0.1) +
coord_map(projection = "albers", lat0 = 45, lat1 = 55) +
scale_fill_continuous(type = "gradient") +
theme(
legend.position = "right",
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank()
)
正如我在评论中提到的,问题在于您将 Group
数据集中的列 group
aes 上,而不是 group
数据映射中的列:
state_initial <- c("AL", "AK", "AZ", "AR", "CA", "CO")
states <- c("alabama", "alaska", "arizona", "arkansas", "california", "colorado")
Group <- c(2.1, 0.0, 1.0, 4.0, 1.0, 6.0)
Group2 <- c(1, 0, 3, 3, 20, 4)
Sum2023 <- c(3, 0, 6, 2, 15, 5)
data1 <- data.frame(state_initial, states, Group, Group2, Sum2023)
library(tidyverse)
us_states <- map_data("state")
us_states %>%
left_join(data1, by = c("region" = "states")) %>%
ggplot(aes(x = long, y = lat, group = group, fill = Group)) +
geom_polygon(color = "gray90", size = 0.1) +
coord_map(projection = "albers", lat0 = 45, lat1 = 55) +
scale_fill_continuous(type = "gradient") +
theme(
legend.position = "right",
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank()
)
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ℹ Please use `linewidth` instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.