Matplotlib颜色y-tick标签通过循环

时间:2016-06-22 15:34:27

标签: python-3.x pandas matplotlib colors axis-labels

给出以下数据框:

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-tick标签与其相应的点的颜色相同。如果我在我的颜色列表中只说了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 个答案:

答案 0 :(得分:2)

您只需在尝试设置颜色之前设置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

另请注意,在设置刻度颜色

之前,您不需要反转颜色列表