为什么图表的标题和x标签都相同,即使我已经将它们包含在for循环中?

问题描述 投票:0回答:1

我希望条形图具有自己的标题和x轴标签,因此我在for循环中包括了plt.titleplt.xlabel。但是,运行代码后,两个图形的标题和x轴标签都相同。第一张图的标题应为Histogram of gender,第二张图的标题应为Histogram of job。我的代码有什么问题,或者我哪部分做错了,尤其是循环?任何帮助将不胜感激!在此先感谢:)

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
from scipy import stats

# first data is age
# 2nd data is gender
# third data is saving
# 4th data is job

data = np.array([[11, "male",1222,"teacher"],[23,"female",333,"student"],
                 [15,"male",542,"security"],[23,"male",4422,"farmer"],[25,"female",553,"farmer"],
                 [22, "male", 221, "teacher"],[27, "male", 333, "agent"],[11, "female", 33, "farmer"]])

data_feature_names = ["age","gender","saving","job"]

# type of the data above
types = ["num","cat","num","cat"]
idx2 = []


for index, _type in enumerate(types):
    if _type == 'cat':
        idx2.append(index)


# Order of x axis label
ss = [["female","male"],["farmer","agent","security","teacher","student"]]


for k in range(0,len(ss)):
    for j in idx2:
        pandasdf = pd.DataFrame(data)
        sns.countplot(x=j, data=pandasdf, order = ss[k])
        plt.title("Histogram of " + data_feature_names[j])
        plt.xlabel(data_feature_names[j])
    plt.show()
python charts label title
1个回答
0
投票

首先,如果将plt.show()移至内部循环,则应最终获得所需的性别和工作直方图结果(但在这种情况下,您将不会最终获得年龄或储蓄的直方图)。您的示例的最后几行将变为:

for k in range(0, len(ss)):
    for j in idx2:
        pandasdf = pd.DataFrame(data)
        ax = sns.countplot(x=j, data=pandasdf, order=ss[k])
        ax.set_title("Histogram of " + data_feature_names[j])
        ax.set_xlabel(data_feature_names[j])
        plt.show()

有几种方法可以简化此过程,以便调试起来更容易一些,并且只需要一个循环。我已经修改并简化了您的示例,以为数据框的每一列生成直方图,并指定分类变量的顺序。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

data = pd.DataFrame(
    [
        [11, "male", 1222, "teacher"],
        [23, "female", 333, "student"],
        [15, "male", 542, "security"],
        [23, "male", 4422, "farmer"],
        [25, "female", 553, "farmer"],
        [22, "male", 221, "teacher"],
        [27, "male", 333, "agent"],
        [11, "female", 33, "farmer"],
    ],
    columns=["age", "gender", "saving", "job"],
)

ordering = {
    "gender": ["female", "male"],
    "job": ["farmer", "agent", "security", "teacher", "student"],
}

for column in data.columns:
    ax = sns.countplot(x=column, data=data, order=ordering.get(column) or None)
    ax.set_title("Histogram of {}".format(column))
    ax.set_xlabel(column)
    plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.