我希望使用ggplot2和地图在美国地图上绘制一组有限的埃博拉病毒数据。
参数是State和Ebola Infected(是/否)
含有该病毒的国家如下:
Texas Yes
Newyork Yes
这些州将以红色着色,而该国的其他州将采用绿色。
我不确定如何对此进行编码,我们将不胜感激。
下面是我可以使用stackoverflow上的其他线程构建的代码
library(ggplot2);
library(maps);
library(plyr);
library(mapproj);
ebolad = read.csv('/usa.csv');
#a data set including the state name and whether it is effected or not (yes/no)
colClasses = c('character', 'character', 'numeric')[[2]];
names(ebolad) = c('col', 'region', 'infected');
ebolad$region = tolower(ebolad$region);
us_state_map = map_data('state');
map_data = merge(ebolad, us_state_map, by = 'region');
map_data = arrange(map_data, order);
ggplot(map_data, aes(x = long, y = lat, group = group)) +
geom_polygon(aes(fill=infected)) +
geom_path(colour = 'gray', linestyle = 2) +
scale_fill_brewer('States affected with EBOLA Virus in USA', palette = 'PuRd') +
coord_map();
有人可以帮我改善情节
答案 0 :(得分:0)
请尝试使用fill
的手动缩放。这是由
scale_fill_brewer(...)
scale_fill_manual('States affected with EBOLA Virus in USA', values=c("green","red"))
但是,这并没有给出最漂亮的绿色和红色。但您可以使用十六进制代码来定义任意颜色,例如values=c("#4daf4a","#e41a1c")
。
infected
的哪个值为红色取决于数据的详细信息。如果未感染状态应为绿色,只需使用values=c("red","green")
切换颜色。
如果您的问题与文件usa.csv
有关,则在没有该文件的情况下很难提供帮助。我通过以下命令生成数据:
ebolad<-data.frame(region=state.name,infected="no",stringsAsFactors=FALSE)
ebolad[ebolad$region %in% c("Texas","New York"),"infected"] <- "yes"
然后,使用前面提到的更改的代码,我得到了一个不错的情节。
答案 1 :(得分:0)
#Code to map USA states affected with Ebola Virus
#import the following libraries
library(ggplot2);
library(maps);
library(plyr);
#begin of code
# read the csv file containing the ebola data for usa (important: replace the directory path)
ebolad = read.csv('usa.csv');
colClasses = c('character', 'character', 'numeric')[[2]];
names(ebolad) = c('col', 'region', 'infected');
ebolad$region = tolower(ebolad$region);
# import the usa state data into local dataset
us_state_map = map_data('state');
# merge ebola data set and usa maps data set
map_data = merge(ebolad, us_state_map, by = 'region');
map_data = arrange(map_data, order);
# storing the data of abbreviated state names to display on the final map
states <- data.frame(state.center, state.abb)
# code to plot the map with state names and colors to distinguish the infected states vs uninfected states
ggplot(map_data, aes(x = long, y = lat, group = group)) +
geom_polygon(aes(fill=infected)) +
geom_path(colour = 'gray', linestyle = 2) +
xlab("Longitude") + ylab("Latitude") +
geom_text(data = states, aes(x = x, y = y, label = state.abb, group = NULL), size = 4)+
scale_fill_manual('States affected with EBOLA Virus in USA', values=c("green4","red3")) +
coord_map(project="globular") +
theme_grey();
#end of code