[英]Plotting dictionary of colors in Python
我正在嘗試使用matplotlib 文檔中的示例在 Python 中顯示自定義 colors 的字典
import numpy as np
import matplotlib.pyplot as plt
th = np.linspace(0, 2*np.pi, 512)
fig, ax1 = plt.subplots(1, 1, figsize=(6, 3))
def color_demo(ax, colors, title):
ax.set_title(title)
for j, c in enumerate(colors):
v_offset = -(j / len(colors))
ax.plot(th, .1*np.sin(th) + v_offset, color=c)
ax.annotate("'C{}'".format(j), (0, v_offset),
xytext=(-1.5, 0),
ha='right',
va='center',
color=c,
textcoords='offset points',
family='monospace')
ax.annotate("{!r}".format(c), (2*np.pi, v_offset),
xytext=(1.5, 0),
ha='left',
va='center',
color=c,
textcoords='offset points',
family='monospace')
ax.axis('off')
mycolors = {
'br': ((84/255), (0/255), (0/255)),
'bl': ((15/255), (123/255), (175/255)),
'yl': ((255/255), (186/255), (45/255)),
'rd': ((237/255), (23/255), (69/255)),
'gy': ((210/255), (210/255), (210/255))
}
color_demo(ax1, mycolors, 'mycolors')
fig.subplots_adjust(**{'bottom': 0.0, 'left': 0.059,
'right': 0.869, 'top': 0.895})
但我收到錯誤ValueError: 'br1' is not a valid value for color
。
這是一個實驗:
>>> mycolors = {
... 'br': ((84/255.0), (0/255.0), (0/255.0)),
... 'bl': ((15/255.0), (123/255.0), (175/255.0)),
... 'yl': ((255/255.0), (186/255.0), (45/255.0)),
... 'rd': ((237/255.0), (23/255.0), (69/255.0)),
... 'gy': ((210/255.0), (210/255.0), (210/255.0))
... }
>>>
>>> for i, c in enumerate(mycolors):
... print(i, c)
...
0 br
1 bl
2 yl
3 rd
4 gy
>>>
這是你期望這段代碼做的嗎? 像這樣遍歷字典實際上是遍歷它的鍵。
我在運行您的代碼時遇到的錯誤說:
ValueError: 'br' is not a valid value for color
它試圖使用第一個鍵( 'br'
)作為顏色,Matplotlib 試圖將其解釋為顏色的名稱,但結果證明“'br' 不是顏色的有效值”。
您應該遍歷字典的值:
for j, c in enumerate(colors.values()):
...
結果 plot:
br
, bl
等...默認不是 colors 。 我想你想要的是:
def color_demo(ax, colors, title):
ax.set_title(title)
for j, c in enumerate(colors):
v_offset = -(j / len(colors))
ax.plot(th, .1*np.sin(th) + v_offset, color=colors[c])
ax.annotate("'C{}'".format(j), (0, v_offset),
xytext=(-1.5, 0),
ha='right',
va='center',
color=c,
textcoords='offset points',
family='monospace')
ax.annotate("{!r}".format(c), (2*np.pi, v_offset),
xytext=(1.5, 0),
ha='left',
va='center',
color=colors[c],
textcoords='offset points',
family='monospace')
ax.axis('off')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.