【问题标题】:Matplotlib Color y-tick Labels via LoopMatplotlib Color y-tick Labels via Loop
【发布时间】:2016-10-24 15:52:37
【问题描述】:

给定以下数据框:

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()

提前致谢!

【问题讨论】:

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


    【解决方案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()
    

    另外请注意,在设置刻度颜色之前,您不需要反转颜色列表

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 2013-01-16
      • 2017-04-22
      • 1970-01-01
      • 2014-12-29
      • 2017-03-18
      • 2016-06-04
      • 1970-01-01
      • 2020-09-28
      相关资源
      最近更新 更多