Advertisement
Guest User

UFOs in the US

a guest
Jan 9th, 2018
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4.  
  5. from mpl_toolkits.basemap import Basemap
  6.  
  7. import matplotlib
  8. from matplotlib.colors import rgb2hex
  9. from matplotlib.patches import Polygon
  10.  
  11. # Read the UFOs dataset, filter by US
  12. ufos = pd.read_csv("ufo_sightings_scrubbed.csv", low_memory = False)
  13. ufos = ufos[["datetime", "country", "state", "latitude", "longitude "]]
  14. ufos.columns = ["datetime", "country", "state", "latitude", "longitude"]
  15. ufos = ufos[ufos.country == "us"]
  16.  
  17. # Map state abbreviations to names
  18. state_names = pd.read_csv("states.csv")
  19. state_names.abbreviation = state_names.abbreviation.str.lower()
  20. state_names_dict = {state.abbreviation: state["name"] for index, state in state_names.iterrows()}
  21. ufos.state.replace(state_names_dict, inplace = True)
  22.  
  23. # Get total UFO sightings by state
  24. num_sightings_by_state = ufos.groupby("state").count().datetime
  25.  
  26. # Set up the map
  27. fig = plt.figure(figsize = (15, 10))
  28. m = Basemap(projection = "merc", llcrnrlon = -130, llcrnrlat = 23, urcrnrlon = -64, urcrnrlat = 50)
  29. us_info = m.readshapefile("st99_d00", "states", drawbounds = True)
  30. colors = {}
  31. state_names = []
  32. cmap = plt.cm.Greens
  33. vmin = num_sightings_by_state.min()
  34. vmax = num_sightings_by_state.max()
  35.  
  36. # Calculate colors
  37. for shape_dict in m.states_info:
  38.     state_name = shape_dict["NAME"]
  39.     sightings = num_sightings_by_state[num_sightings_by_state.index == state_name][0]
  40.     colors[state_name] = cmap(np.sqrt((sightings - vmin) / (vmax - vmin)))[:3]
  41.     state_names.append(state_name)
  42.    
  43. # Show polygons with their respective colors
  44. ax = plt.gca()
  45. for nshape, seg in enumerate(m.states):
  46.     color = rgb2hex(colors[state_names[nshape]])
  47.     poly = Polygon(seg, facecolor = color, edgecolor = color)
  48.     ax.add_patch(poly)
  49.  
  50. # Add title and colorbar
  51. plt.title("UFO Sightings by State (Contiguous US)")
  52. colorbar_ax = fig.add_axes([0.95, 0.15, 0.02, 0.7])
  53. matplotlib.colorbar.ColorbarBase(colorbar_ax, cmap = cmap, norm = matplotlib.colors.Normalize(vmin, vmax))
  54. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement