2016-07-29 124 views
0

我有一個代碼片段,與Python 3一起工作正常,但不與Python 2一起使用。 我試圖使用RGB代碼來定義調色板:與Python 3,但是Python 2種顏色顯示他們全部黑...Matplotlib:RGB顏色與Python 2顯示爲黑色

下面是一個非常簡單的代碼片段,顯示這個怪異的行爲:

%matplotlib inline 
import pandas as pd 
import matplotlib.pylab as plt 
import numpy as np 

colors = { 
    'A': (234, 142, 142), 
    'B': (255, 224, 137), 
    'C': (189, 235, 165)} 

df = pd.DataFrame(np.random.randn(20, 3), columns=list('ABC')).cumsum() 

fig, ax = plt.subplots() 
for col in df.columns: 
    ax.plot(df.index.tolist(), df[col].values, color=(tuple(i/255 for i in colors[col]))) 
plt.show() 

的Python 2

Using Python2

的Python 3(OK)

Using Python3

那是一個錯誤或matplotlib處理RGB顏色故意以不同的方式?我應該如何調整我的代碼?

軟件|版本 Python | 2.7.11 64bit
IPython | 4.0.3
操作系統| Windows 7 6.1.7601 SP1
matplotlib |在這條線發生1.5.1

+5

Python 2和Python 3對於除法運算符有所不同。是否有可能,你的整數部門負責 - > 234/255 = 0 – sascha

回答

1

問題:

i/255 for i in colors[col] 

這是因爲整數除法是在Python 2和Python不同3.

的Python 2

>>> 2/3 
>>> 0 

Python 3中

>>> 2/3 
>>> 0.66... 

爲了得到t他在Python 2相同的行爲,你可以使用:

from __future__ import division 
+0

我更快:-)。但很好的答案!你也可以在你的答案中引入//運算符! – sascha

+0

Aaaaah當然:) 謝謝! – jodoox

1

它看起來像你從來沒有在Python 2和Python 3師聽到不同的行爲不久 - 它添加到你的Python代碼頂部 - from __future__ import division。 Python 2會糾正它不明顯的行爲,python 3會忽略這個聲明 - 它已經被修復了。

相關問題