2016-06-22 45 views
1

的y蜱标签鉴于以下数据帧:Matplotlib颜色经由环路

import pandas as pd 
import numpy as np 
df=pd.DataFrame({'A':['A','B','C','D','E','F','G','H','I','J','K','L','M','N'], 
       'B':[20,25,39,43,32,17,40, 40, 34, 56, 76, 23, 54, 34]}) 

我想创建气泡图,其中每个y-蜱标签是颜色作为其相应的点相同。下面的代码很好用,如果我只在我的颜色列表中说4行数据和4种颜色。但是,由于某些原因,当我有超过9行左右的数据(以及我的颜色列表中的颜色)时,它仅占用l.set_color(i)行中的前9个颜色元素。任何想法为什么会发生这种情况?迭代时它是否是zip的限制?与数据框相关?

import matplotlib.pyplot as plt 
import matplotlib.ticker as mtick 
labels=df.A[::-1] 
vals=df.B[::-1] 
ind=np.arange(len(labels)) 
colors1=['r','g','b','c','y','y','y','g','b','c','y','y','y','g'] 
fig, ax = plt.subplots(1, 1, figsize = (6,4)) 
for i in ind: 
    plt.plot(vals[i],i,marker='o',markeredgecolor='none', markersize=17, alpha=.5, linestyle='none', color=colors1[i]) 
ax.tick_params(axis='x',which='both',bottom='on',top='off',color='grey',labelcolor='grey') 
ax.tick_params(axis='y',which='both',left='off',right='off',color='grey',labelcolor='grey') 
ax.spines['top'].set_visible(False);ax.spines['right'].set_visible(False); 
ax.spines['bottom'].set_visible(False);ax.spines['left'].set_visible(False) 

ax.set_xlim([0,50]) 
ax.set_ylim([min(ind)-1,max(ind)+1]) 
fontcols=colors1[::-1] 
for l,i in zip(ax.yaxis.get_ticklabels(),fontcols): 
    l.set_color(i) 
    l.set_fontsize(11) 
    print(l,i) #This shows that only 9 members are being colored for some reason 
plt.yticks(ind,labels,fontsize=14) 

plt.show() 

enter image description here

提前感谢!

回答

1

在试图设置颜色之前,您只需设置yticks即可。实际上,matplotlib在默认情况下会创建9个刻度,您可以设置它们的颜色,然后告诉它你需要14个刻度。只需一点点重新排序,这一切工作:

import matplotlib.pyplot as plt 
import matplotlib.ticker as mtick 
import pandas as pd 
import numpy as np 
df=pd.DataFrame({'A':['A','B','C','D','E','F','G','H','I','J','K','L','M','N'], 
       'B':[20,25,39,43,32,17,40, 40, 34, 56, 76, 23, 54, 34]}) 

labels=df.A[::-1] 
vals=df.B[::-1] 
ind=np.arange(len(labels)) 
colors1=['r','g','b','c','y','y','y','g','b','c','y','y','y','g'] 
fig, ax = plt.subplots(1, 1, figsize = (6,4)) 
for i in ind: 
    plt.plot(vals[i],i,marker='o',markeredgecolor='none', markersize=17, alpha=.5, linestyle='none', color=colors1[i]) 
ax.tick_params(axis='x',which='both',bottom='on',top='off',color='grey',labelcolor='grey') 
ax.tick_params(axis='y',which='both',left='off',right='off',color='grey',labelcolor='grey') 
ax.spines['top'].set_visible(False);ax.spines['right'].set_visible(False); 
ax.spines['bottom'].set_visible(False);ax.spines['left'].set_visible(False) 

ax.set_xlim([0,80]) # I increased this to fit all your data in 
ax.set_ylim([min(ind)-1,max(ind)+1]) 
fontcols=colors1  # NOTE: you don't need to reverse this 
plt.yticks(ind,labels,fontsize=14) 
for l,i in zip(ax.yaxis.get_ticklabels(),fontcols): 
    l.set_color(i) 
    l.set_fontsize(11) 
    print(l,i) 

plt.show() 

enter image description here

另外请注意,你不需要设置刻度颜色

+0

哇,谢谢之前扭转颜色列表!奇迹般有效。 –