用Python中的颜色字典绘制不同颜色的线条

时间:2013-10-21 07:54:16

标签: python matplotlib pandas matplotlib-basemap

我试图用15种不同颜色绘制地图上15种不同风暴的路径。路径的颜色应取决于风暴的名称。例如,如果风暴的名称是AUDREY,风暴路径的颜色应该是地图上的红色。有人可以帮助/指出我正确的方向吗?

以下是我的代码部分:

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)

以下是我不断收到的错误消息:

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'                                                                                 
 >>> 

1 个答案:

答案 0 :(得分:1)

您正在错误地访问字典条目。首先,你执行此操作names = list(data.Name)。因此名称的类型为lists。然后你像这样调用字典:color_dict[names]。问题不是设置颜色,而是如何尝试访问字典(list不是有效密钥)。

将其更改为:

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.

它会起作用。

此外,您的错误消息显示为plt.plot(x,y,'y-',color=colors[names], linewidth=2 ),但在您的代码中,您有color=colors_dict[names]。您确定发布了正确的代码吗?