Creating a map by R-Studio

I am going to generate a map, find a sample code at following website:
http://www.briansarnacki.com/an-easy-way-to-map-data-in-r-with-plotly/

Here is the code:
library(plotly)
mh<- read.csv("mentalhealth.csv",header=T,sep=',')

plot_ly(type="choropleth", locations=mh$state,
locationmode="USA-states", z=mh$rank) %>%
layout(geo=list(scope="usa"),)

When running the code, I got error message:
Error in layout.plotly(., geo = list(scope = "usa"), ) :
argument is missing, with no default

What is wrong with it? Thank you.
By the way, paste the data here:
rank state
1 CT
2 MA
3 VT
4 SD
5 MN
6 NJ
7 IA
8 ND
9 PA
10 ME
11 DE
12 NY
13 AK
14 MD
15 IL
16 HI
17 MI
18 DC
19 KY
20 NH
21 KS
22 NM
23 CA
24 OK
25 CO
26 OH
27 NE
28 FL
29 WY
30 WA
31 MO
32 TX
33 NC
34 GA
35 WI
36 RI
37 SC
38 VA
39 MT
40 UT
41 TN
42 LA
43 WV
44 MS
45 IN
46 AL
47 AR
48 ID
49 OR
50 AZ
51 NV

I think it's just a typo — you have a stray comma at the end of layout(geo=list(scope="usa"),), implying that you're supplying another argument to layout. Remove the comma, and all is well:

library(plotly)
mh <- data.frame(
  rank = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
           19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
           31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
           43, 44, 45, 46, 47, 48, 49, 50, 51),
  state = c("CT", "MA", "VT", "SD", "MN", "NJ", "IA", "ND", "PA", "ME",
            "DE", "NY", "AK", "MD", "IL", "HI", "MI", "DC",
            "KY", "NH", "KS", "NM", "CA", "OK", "CO", "OH",
            "NE", "FL", "WY", "WA", "MO", "TX", "NC", "GA",
            "WI", "RI", "SC", "VA", "MT", "UT", "TN", "LA",
            "WV", "MS", "IN", "AL", "AR", "ID", "OR", "AZ",
            "NV")
)

plot_ly(
  type = "choropleth",
  locations = mh$state,
  locationmode = "USA-states",
  z = mh$rank
) %>%
  layout(geo = list(scope = "usa"))

3 Likes

5 posts were split to a new topic: Plotly map does not display in viewer pane