首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >matplotlib subplot -颜色是交替的

matplotlib subplot -颜色是交替的
EN

Stack Overflow用户
提问于 2018-04-19 13:51:11
回答 1查看 52关注 0票数 0

我这里有一个可以打印各种子图的代码。然而,第二个子图的颜色总是交替的。我如何解决这个问题,使所有的颜色都一致?

As you can see, the second subplot has its colors opposite of the first and third. This is consistent for every column

代码语言:javascript
复制
hrlist = [hrdata2015, hrdata2016, hrdata2017]
titles = ["2015", "2016", "2017"]
columns = ["Sex","Education Level","Salary Plan","Grade",
       "Contract Type","Citizenship", "Division"]


for h in columns:

    plt.figure(figsize=(40,40))
    j = 0


    for i in range(len(hrlist)):
        j +=1
        plt.subplot(2,2,j)

        ax1 = sns.countplot(data=hrlist[i],x= h,hue="HR Status", order = hrlist[i][h].value_counts().index)
        ax1.set_title(titles[i])
        ax1.legend(loc = "upper right", prop={'size': 12})
        if(h=="Education Level" or h=="Grade"):
            plt.xticks(fontsize = 9)
        elif (h == "Division"):
            plt.xticks(rotation = 60, fontsize = 8)
        else:
            plt.xticks(fontsize = 12)
        for p in ax1.patches:
            height = p.get_height()
            ax1.text(p.get_x()+p.get_width()/2,
                 height + 1,
                 '{:1.0f}'.format(height,0),
                 ha="center",rotation=0) 


    plt.tight_layout()
    plt.subplots_adjust(top=0.948,
                    bottom=0.115,
                    left=0.052,
                    right=0.986,
                    hspace=0.533,
                    wspace=0.128)
    plt.show()
EN

回答 1

Stack Overflow用户

发布于 2018-04-19 14:58:09

我的猜测是,hrdata2016的第一行恰好是“非活动的”,而hrdata2015hrdata2017的第一行都是“活动的”。由于您没有定义色调(颜色)顺序,因此使用了DataFrame中的顺序。按hue_order参数定义色调(颜色)顺序,如下所示:

代码语言:javascript
复制
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df1 = pd.DataFrame([['F', 'Active'],
                    ['M', 'Inactive'],
                    ['F', 'Inactive'],
                    ['M', 'Active'],
                    ['F', 'Inactive'],
                    ['M', 'Inactive'],
                    ['F', 'Active']], columns=['Sex', 'HR Status'])
df2 = df1.drop(0)
df3 = df2.drop(1)
hrlist = [df1, df2, df3]

h = 'Sex'
for i in range(len(hrlist)):
    plt.subplot(2,2,i+1)
#     ax1 = sns.countplot(data=hrlist[i], x=h, hue="HR Status", order=hrlist[i][h].value_counts().index)
    ax1 = sns.countplot(data=hrlist[i], x=h, hue="HR Status",
                        order=hrlist[i][h].value_counts().index,
                        hue_order=hrlist[i]["HR Status"].value_counts().index)
plt.show()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49913623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档