Plot lines in different colors from color dictionary in Python
You're accessing the dictionary entries incorrectly. First off you do this names = list(data.Name)
. So names is of type lists
. Then you call dictionary like this: color_dict[names]
. The problem is not setting the colour but how you try to access the dictionary (list
is not a valid key).
Change it to something like:
for colourName in color_dict.keys():
plt.plot(x,y,'y-',color=color_dict[colourName], linewidth=2 ) # You need to use different data for the data series here.
And it'll work.
Also, your error message reads plt.plot(x,y,'y-',color=colors[names], linewidth=2 )
but in your code you've got color=colors_dict[names]
. Are you sure you posted the right code?
mikez1
Updated on June 04, 2022Comments
-
mikez1 almost 2 years
I'm trying to plot the path of 15 different storms on a map in 15 different colors. The color of the path should depend on the name of the storm. For example if the storm's name is AUDREY, the color of the storm's path should be red on the map. Could some please help/point me in the right direction?
Here's the part of my code:
import numpy as np from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import csv, os, scipy import pandas from PIL import * data = np.loadtxt('louisianastormb.csv',dtype=np.str,delimiter=',',skiprows=1) '''print data''' fig = plt.figure(figsize=(12,12)) ax = fig.add_axes([0.1,0.1,0.8,0.8]) m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57., projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60., resolution ='l',area_thresh=1000.) m.bluemarble() m.drawcoastlines(linewidth=0.5) m.drawcountries(linewidth=0.5) m.drawstates(linewidth=0.5) # Creates parallels and meridians m.drawparallels(np.arange(10.,35.,5.),labels=[1,0,0,1]) m.drawmeridians(np.arange(-120.,-80.,5.),labels=[1,0,0,1]) m.drawmapboundary(fill_color='aqua') color_dict = {'AUDREY': 'red', 'ETHEL': 'white', 'BETSY': 'yellow','CAMILLE': 'blue', 'CARMEN': 'green', 'BABE': 'purple', 'BOB': '#ff69b4', 'FREDERIC': 'black', 'ELENA': 'cyan', 'JUAN': 'magenta', 'FLORENCE': '#faebd7', 'ANDREW': '#2e8b57', 'GEORGES': '#eeefff', 'ISIDORE': '#da70d6', 'IVAN': '#ff7f50', 'CINDY': '#cd853f', 'DENNIS': '#bc8f8f', 'RITA': '#5f9ea0', 'IDA': '#daa520'} # Opens data file witn numpy '''data = np.loadtxt('louisianastormb.csv',dtype=np.str,delimiter=',',skiprows=0)''' '''print data''' colnames = ['Year','Name','Type','Latitude','Longitude'] data = pandas.read_csv('louisianastormb.csv', names=colnames) names = list(data.Name) lat = list(data.Latitude) long = list(data.Longitude) colorName = list(data.Name) #print lat #print long lat.pop(0) long.pop(0) latitude= map(float, lat) longitude = map(float, long) x, y = m(latitude,longitude) #Plots points on map for colorName in color_dict.keys(): plt.plot(x,y,'-',label=colorName,color=color_dict[colorName], linewidth=2 ) lg = plt.legend() lg.get_frame().set_facecolor('grey') plt.title('20 Hurricanes with Landfall in Louisiana') #plt.show() plt.savefig('20hurpaths1.jpg', dpi=100)
Here's the error message that I keep getting is:
Traceback (most recent call last): File "/home/mikey1/lstorms.py", line 51, in <module> plt.plot(x,y,'y-',color=colors[names], linewidth=2 ) TypeError: unhashable type: 'list' >>>
-
mikez1 over 10 yearsOh ok. Sorry I'm a newb at this. I just looked at a few examples on python dictionaries but it's still confusing. What would be the best way to access the dictionary for what I'm trying to do?
-
mikez1 over 10 yearsThank you so much!!! Sorry about that the code is the same but I just changed it from color to color_dict to keep everything unique.
-
Aleksander Lidtke over 10 yearsNo worries mate. For future reference it's best if the keys are of
type <int>
ortype <str>
. And there's a simple example how to programmatically access dictionaries entries in my answer. Does it work now? If not update the question with new problem, if it does would be good if you accepted the answer. -
mikez1 over 10 yearsThank you so much!!! I finally got rid of that error. However the lines do not show up on my map. Is there anyway to fix this?
-
Aleksander Lidtke over 10 yearsCan you post the entire code of yours (with import statements etc.)?
-
Aleksander Lidtke over 10 yearsI see. Well so, to be honest, I never used
Basemap
. Didn't even know it existed but it'a pretty cool and relevant to what I do, so thanks for posting this here ;) Two things which I'd investigate: 1) uncommentplt.show()
and refresh the figure (e.g. maximise it on the screen). 2) Are you certain thisx, y = m(latitude,longitude)
does what you want it to return? (here comes my lack of familiarity withBasemap
...)