I have written the following code:
library(ozmaps)
oz(states = TRUE, coast = TRUE,
ylim = NULL, add = FALSE, ar = 1, eps = 0.25)
That generates:
I wonder how to add the names of the states on the map? If the whole process can be done by "map" package, it is fine as well.
Thanks.
I'm not familiar with package ozmaps. I could not find data for the state names and latitude and longitude values for state centroids within the package.
A quick internet search produced some representative state data from https://www.distancelatlong.com/distancecalculator/country/australia/
You can adjust this data or find a better source, so this should be a start.
library(tibble)
library(ggplot2)
library(ozmaps)
ggplot(ozmap_states)+
geom_sf()+
geom_text(data = oz_states, aes(long, lat, label = state))+
theme_void()
data
oz_states <- tribble(
~state, ~lat, ~long,
"Australian Capital Territory", -35.3546004, 149.2113468,
"New South Wales", -33.42004148, 151.3000048,
"Northern Territory", -13.81617348, 131.816698,
"Queensland", -26.67998777, 153.0500272,
"South Australia", -34.28293455, 140.6000378,
"Tasmania", -40.83292234, 145.1166613,
"Victoria", -37.73119953, 142.0234135,
"Western Australia", -33.58287392, 120.0333345
)
Created on 2021-03-29 by the reprex package (v1.0.0)
Related
I have been trying to convert the latitude and longitude into multipolygon object so that that I can use tmap library to plot it, but I am not able to that. Converting useing st_as_sf is not wroking, can some help me? I am attaching sample data set.
coor<-structure(list(Type = c("Registry", "Registry", "Registry", "Registry", "Platform", "Registry"),`Location of coordinating center` = c("USA","USA", "USA", "USA", "United Kingdom", "United Kingdom"),`3ISO code` = c("USA", "USA", "USA", "USA", "GBR", "GBR"), `WHO region code` = c("AMR","AMR", "AMR", "AMR", "EUR", "EUR"), city = c("Philadelphia","Chicago", "Washington", "Alexandria", "London", "Manchester"), lat = c(32.7761, 41.8373, 38.9047, 38.8185, 51.50853, 53.4794), lng = c(-89.1221, -87.6862, -77.0163, -77.0861, -0.12574, -2.2453)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
Two comments to this:
you are unlikely to convert your data to multiopolygon object, since you have only a single coordinate pair for each city / that spells points to me, not polygons
you were on a right track with sf::st_as_sf()
What you need to do in your st_as_sf call to make it work properly is
specify columns in your data frame that have coordinate information and
give a meaning to the figures (are they degrees? meters? or has an American been feeling patriotic and encoded the data in feet?) you use a coordinate reference system (crs) for that.
For long lat data EPSG:4326 is usually a good default.
library(sf)
library(tmap)
sf_coords <- coor %>%
st_as_sf(coords = c("lng", "lat"), crs = 4326)
tmap_mode("view")
tm_shape(sf_coords) +
tm_bubbles(size = 5, col = "red", id = "city") +
tm_basemap(leaflet::providers$Stamen.Watercolor)
I ran 2 aggregate commands:
Outright_owners = aggregate(csv_data$Owned...outright~csv_data$State, csv_data, FUN = sum)
and
Mortgage_owners = aggregate(csv_data$Owned...with.a.mortgage~csv_data$State, csv_data, FUN = sum)
This is the output of Outright_owners aggregate:
csv_data$State
csv_data$Owned...outright
New South Wales
819828
Northern Territory
9297
Queensland
448627
South Australia
202917
Tasmania
69784
Victoria
665363
Western Australia
234608
This is the output of Mortgage_owners aggregate:
csv_data$State
csv_data$Owned...with.a.mortgage
New South Wales
824168
Northern Territory
18497
Queensland
533879
South Australia
218264
Tasmania
65921
Victoria
697520
Western Australia
300355
I want code that would create a stacked bar-plot that would look something like this
I haven't tried anything specific yet, so I don't have any minimum reproducible code. I'm not sure where even to begin.
Thanks in advance :)
Update:
Something like this:
To show the data better I would log the y scale:
join the data with left_join
bring it to long form with pivot_longer
apply geom_col
use log y.
With ggplot2
library(tidyverse)
left_join(df1, df2, by="State") %>%
pivot_longer(
cols = -State
) %>%
ggplot(aes(x = State, y=log(value), fill=name, label=value))+
geom_col() +
geom_text(size = 5, position = position_stack(vjust = 0.9))
With base R before base R, I used tidyr package to bring it to wide format.
df1_w <- df1 %>%
pivot_wider(
names_from = State,
values_from = mortgage
)
df2_w <- df2 %>%
pivot_wider(
names_from = State,
values_from = mortgage
)
Plot with base R
data <- as.matrix(data.frame(rbind(df1_w, df2_w)))
rownames(data) <- c("outright", "mortgage")
barplot(data,
col = c("green", "red"))
legend("topright",
legend = c("outright", "mortgage"),
fill = c("green", "red"))
data:
df1 <- structure(list(State = c("New South Wales", "Northern Territory",
"Queensland", "South Australia", "Tasmania", "Victoria", "Western Australia"
), outright = c(819828L, 9297L, 448627L, 202917L, 69784L, 665363L,
234608L)), class = "data.frame", row.names = c(NA, -7L))
df2 <- structure(list(State = c("New South Wales", "Northern Territory",
"Queensland", "South Australia", "Tasmania", "Victoria", "Western Australia"
), mortgage = c(824168L, 18497L, 533879L, 218264L, 65921L, 697520L,
300355L)), class = "data.frame", row.names = c(NA, -7L))
I plotted a dot density map of the Australian states and am now trying to plot a chloropleth map of the Australian states using the leaflet package and color each state by the count value. I have the following data frame
state count latitude longitude
Australian Capital Territory 125 ... ...
New South Wales 45
Northern Territory 75
Queensland 12
South Australia 245
Tasmania 4895
Victoria 279
The following is the code I used to plot the dot density map
leaflet(aus_state_counts) %>%
addTiles() %>%
addCircleMarkers(
layerId = ~state,
label = ~state,
radius = ~count
) %>%
fitBounds(lng1 = max(aus_state_counts$longitude) ,lat1 = max(aus_state_counts$latitude),
lng2 = min(aus_state_counts$longitude) ,lat2 = min(aus_state_counts$latitude)
)
I am unsure how to plot the states on the map? Do I need additional information for this?
For a choropleth map you will need some spatial polygon data in the form of a shape file (.shp) or GeoJSON (.geojson). Below should work.
library(sf)
library(leaflet)
library(dplyr)
# GeoJSON Data
states <- read_sf("https://raw.githubusercontent.com/rowanhogan/australian-states/master/states.geojson")
counts <- data.frame(state=c("Australian Capital Territory", "New South Wales", "Northern Territory", "Queensland",
"South Australia", "Tasmania", "Victoria"), count=c(125,45,75,12,245,4895,279))
# Join to count data
data <- states %>%
dplyr::left_join(counts, by=c("STATE_NAME" = "state"))
# Specify choropleth colors
pal <- colorQuantile("Blues", domain = data$count)
# Plot Map
leaflet(data) %>%
addTiles() %>%
addPolygons(fillColor=~pal(count), fillOpacity=0.8, color="white", weight=1)
I have some data in the UK and I need to introduce a map of all 9 regions of England. I tried using library(maps) but the plots I get do not have any regional information and I just end up with the whole of the United Kingdom.
Ideally i am looking for a result like this
https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/English_regions_2009.svg/370px-English_regions_2009.svg.png
(I cant actually attach pictures due to the lack of reputation points,apologies!)
My data has a column for regions with character values:
EastMid
EastEng
London
NorthEast
NorthWest
SouthEast
SouthWest
WestMid
Yorkshire
I would then go on to map by color regions with different attributes
How would I go on about this?
First, as Andrew wrote you need to find and download shapefiles with necessary regions. Such split as you need is usually called historical regions or standard statistical regions. You might want to check this site: http://www.natureonthemap.naturalengland.org.uk/
Second, you read shapefile and merge with referendum data. Make sure that region names at the referendum file are exactly the same as in geospatial file (I use file downloaded from the site mentioned above, if you download another shapefile the names probably will be different):
library(rgdal)
library(tmap)
geoEN = readOGR(".", "maghistengland")
In this case region names are stored in NAME (in another shapefile attribute name can be different). You can check what information consists of geospatial file by:
ogrInfo(".", "maghistengland")
For the purpose of the example I am creating fake figures of voting results.
votes = as.data.frame(
cbind(
c("EAST MIDLANDS",
"EAST OF ENGLAND",
"LONDON",
"NORTH EAST",
"NORTH WEST",
"SOUTH EAST",
"WEST MIDLANDS",
"YORKSHIRE AND THE HUMBER",
"SOUTH WEST"),
c(60, 65, 55, 50, 45, 40, 35, 30, 30),
c(40, 35, 45, 50, 55, 60, 65, 70, 70)
), stringsAsFactors = FALSE)
names(votes) = c("Regions", "Yes", "No")
votes$Yes = as.numeric(votes$Yes)
votes$No = as.numeric(votes$No)
votes$Result = colnames(votes)[max.col(votes[,2:3])+1]
Now we can merge both files:
mapEN = append_data(geoEN, votes, key.shp = "NAME", key.data = "Regions")
Third, create necessary charts. Here are three examples. You can play with number of groups (n = 2, 3, 4..), colors etc.
tm_shape(mapEN) +
tm_fill("Yes", title = "This is a title", palette = "Blues", n=4) +
tm_borders(alpha=.5)
tm_shape(mapEN) +
tm_fill("No", title = "This is a title", palette = "Reds", n=5) +
tm_borders(alpha=.5)
tm_shape(mapEN) +
tm_fill("Result", palette = c("Red", "Blue")) +
tm_borders(alpha=.5)
I would like to use R to generate a very basic world map with a specific set of countries filled with a red colour to indicate that they are malaria endemic countries.
I have a list of these countries in a data frame but am struggling to overlay them on a world map.
I have tried using the wrld_simpl object and also the joinCountryData2Map method in the rworldmap package.
I would comment on this answer to prevent addition of a possibly redundant question but I do not have enough reputation at the moment, apologies for this.
https://stackoverflow.com/a/9102797/1470099
I am having difficulty understanding the arguments given to the plot() command - I wondered if there was just an easy way to tell R to plot all of the country NAMEs in my list on the wrld_simpl map instead of using grepl() etc. etc.
plot(wrld_simpl,
col = c(gray(.80), "red")[grepl("^U", wrld_simpl#data$NAME) + 1])
Using the rworldmap package, you could use the following:
library(rworldmap)
theCountries <- c("DEU", "COD", "BFA")
# These are the ISO3 names of the countries you'd like to plot in red
malDF <- data.frame(country = c("DEU", "COD", "BFA"),
malaria = c(1, 1, 1))
# malDF is a data.frame with the ISO3 country names plus a variable to
# merge to the map data
malMap <- joinCountryData2Map(malDF, joinCode = "ISO3",
nameJoinColumn = "country")
# This will join your malDF data.frame to the country map data
mapCountryData(malMap, nameColumnToPlot="malaria", catMethod = "categorical",
missingCountryCol = gray(.8))
# And this will plot it, with the trick that the color palette's first
# color is red
EDIT: Add other colors and include picture
## Create multiple color codes, with Burkina Faso in its own group
malDF <- data.frame(country = c("DEU", "COD", "BFA"),
malaria = c(1, 1, 2))
## Re-merge
malMap <- joinCountryData2Map(malDF, joinCode = "ISO3",
nameJoinColumn = "country")
## Specify the colourPalette argument
mapCountryData(malMap, nameColumnToPlot="malaria", catMethod = "categorical",
missingCountryCol = gray(.8), colourPalette = c("red", "blue"))
Try using googleVis package and use gvisGeoMap Functions
e.g.
G1 <- gvisGeoMap(Exports,locationvar='Country',numvar='Profit',options=list(dataMode='regions'))
plot(G1)
library(maptools)
data(wrld_simpl)
myCountries = wrld_simpl#data$NAME %in% c("Australia", "United Kingdom", "Germany", "United States", "Sweden", "Netherlands", "New Zealand")
plot(wrld_simpl, col = c(gray(.80), "red")[myCountries+1])